I have a Java 8 stream of objects and I would like to ignore the objects after a given predicate is matched.
Example : I would like to keep all the strings up-to the "BREAK" one (and including it).
public List<String> values = Arrays.asList("some", "words", "before", "BREAK", "AFTER");
@Test
public void testStopAfter() {
Stream<String> stream = values.stream();
//how to filter stream to stop at the first BREAK
//stream = stream.filter(s -> "BREAK".equals(s));
final List<String> actual = stream.collect(Collectors.toList());
final List<String> expected = Arrays.asList("some", "words", "before", "BREAK");
assertEquals(expected, actual);
}
As it is it fails (expected:<[some, words, before, BREAK]> but was:<[some, words, before, BREAK, AFTER]>), and if I uncomment the filter, I only get the "BREAK"
I am thinking of a statefull Predicate (see my answer below) but I was wandering if there was a nicer solution ?