Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if-else logic in Java 8 stream forEach

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())); 
like image 492
user3768533 Avatar asked Jun 24 '16 19:06

user3768533


People also ask

How do you do if else in Java stream?

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() .

How do you write if else condition in Java 8?

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.

Can we use forEach in streams Java?

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.

Can we use if condition in lambda expression Java?

The 'if-else' condition can be applied as a lambda expression in forEach() function in form of a Consumer action.


1 Answers

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);                 }             }     ); 
like image 146
Alex Shesterov Avatar answered Sep 16 '22 11:09

Alex Shesterov