Skip to content

Commit

Permalink
StreamExTest: maxWithStop example
Browse files Browse the repository at this point in the history
  • Loading branch information
amaembo committed Jul 1, 2016
1 parent 0f9e76e commit b733887
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/test/java/one/util/streamex/StreamExTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1805,4 +1805,26 @@ public void testPrefix() {
streamEx(() -> IntStreamEx.range(10000).boxed().unordered(), s -> assertEquals(49995000, s.get().prefix(
Integer::sum).mapToInt(Integer::intValue).max().getAsInt()));
}

/**
* Returns maximal stream value short-circuiting when stopValue is reached
* @param stream stream to process
* @param comparator comparator to compare stream values
* @param stopValue value to short-circuit at
* @return optional describing maximal value or empty optional if input stream is empty
*/
static <T> Optional<T> maxWithStop(StreamEx<T> stream, Comparator<T> comparator, T stopValue) {
return stream.prefix(BinaryOperator.maxBy(comparator)).takeWhileInclusive(Predicate.isEqual(stopValue).negate())
.collect(MoreCollectors.last());
}

@Test
public void testMaxWithStop() {
// Infinite stream, stop is reached
assertEquals(Optional.of(1000), maxWithStop(IntStreamEx.of(new Random(1), 0, 1001).boxed(), Comparator
.naturalOrder(), 1000));
// FInite stream, stop is not reached
assertEquals(Optional.of(999), maxWithStop(IntStreamEx.of(new Random(1), 10000, 0, 1000).boxed(), Comparator
.naturalOrder(), 1000));
}
}

0 comments on commit b733887

Please sign in to comment.