[英]How do I make a Stream `max` early-terminate?
我正在針對 OpenJDK 16 寫作並試圖充分利用流。 我有一個案例需要混合Stream.max
,獲取此比較器的元素:
public static final Comparator<Solution> byMatched =
Comparator.comparing(sol -> sol.pairs.size());
表示最大的pairs
集合; 但如果這個size()
達到已知的上限,我也需要提前終止。 關於我認為我可以使用內置插件獲得的最接近的是
public Solution best() {
return StreamSupport.stream(this, true)
.takeWhile(
solution -> solution.pairs().size() < problem.animals().size()
)
.max(Solution.byMatched)
.get();
}
this
實現了Spliterator<Solution>
。 這種方法是不正確的,因為雖然它會提前終止,但第一個達到最大問題大小的解決方案會被takeWhile
丟棄。
是否有內置的流方法應用max
,但在(並包括第一個值!)給定的謂詞變為true
?
您可以使用有狀態謂詞,該謂詞在遇到超過閾值的第一個輸入之前返回 true。
像這樣的東西:
class BoundedPredicate<T, V extends Comparable<V>> implements Predicate<T> {
private V boundary; //the boundary
private Function<T, V> extractor; //the value extractor to get what's needed for the comparison
private boolean boundaryHit; //the flag that keeps track of whether the boundary was hit
public BoundedPredicate(V boundary, Function<T, V> extractor) {
super();
this.boundary = boundary;
this.extractor = extractor;
}
public boolean test(T value) {
//boundary was hit last time so return false now
if( boundaryHit) {
return false;
}
//check boundary and if it was hit, update the flag
if( boundary.compareTo(extractor.apply(value)) <= 0) {
boundaryHit = true;
}
return true;
}
}
和用法:
return StreamSupport.stream(this, true)
.takeWhile(
new BoundedPredicate<Integer, Integer>(problem.animals().size(), solution -> solution.pairs().size() )
)
.max(Solution.byMatched)
.get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.