I have a requirement to log/sysout
the filtered values in Java Streams. I am able to log/sysout
the non-filtered value using peek()
method
As there's no way to run terminal actions on elements matching opposite filters on the same stream, the best option may be just to use a condition in a peek
's consumer.
That avoids traversing the stream/collection twice.
List persons = Arrays.asList(new Person("John"), new Person("Paul"));
//A consumer that only logs "John" persons
Consumer logger = p -> {
if ("John".equals(p.getName())) //condition in consumer
System.out.println("> " + p.getName());
};
Then we can pass that consumer to peek
, only filtering for the ultimate action after that:
List nonJohns = persons.stream()
.peek(logger)
.filter(p -> !"John".equals(p.getName()))
.collect(Collectors.toList());