What I want to do is shown below in 2 stream calls. I want to split a collection into 2 new collections based on some condition. Ideally I want to do it in 1. I've seen conditions used for the .map function of streams, but couldn't find anything for the forEach. What is the best way to achieve what I want?
animalMap.entrySet().stream() .filter(pair-> pair.getValue() != null) .forEach(pair-> myMap.put(pair.getKey(), pair.getValue())); animalMap.entrySet().stream() .filter(pair-> pair.getValue() == null) .forEach(pair-> myList.add(pair.getKey()));
Conventional if/else Logic Within forEach() First of all, let's create an Integer List and then use conventional if/else logic within the Integer stream forEach() method: List<Integer> ints = Arrays. asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); ints. stream() .
One Line if-else Statement Using filter in Java 8The streams filter method takes a Predicate and behaves like if-else in Java language. The above program instantiates a list using Arrays. asList() method.
Stream forEach() method in Java with examplesStream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
The 'if-else' condition can be applied as a lambda expression in forEach() function in form of a Consumer action.
Just put the condition into the lambda itself, e.g.
animalMap.entrySet().stream() .forEach( pair -> { if (pair.getValue() != null) { myMap.put(pair.getKey(), pair.getValue()); } else { myList.add(pair.getKey()); } } );
Of course, this assumes that both collections (myMap
and myList
) are declared and initialized prior to the above piece of code.
Update: using Map.forEach
makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:
animalMap.forEach( (key, value) -> { if (value != null) { myMap.put(key, value); } else { myList.add(key); } } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With