Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform nested 'if' statements using Java 8/lambda?

Tags:

I have the following code and would like to implement it using lambda functions just for fun. Can it be done using the basic aggregate operations?

List<Integer> result = new ArrayList<>();  for (int i = 1; i <= 10; i++) {     if (10 % i == 0) {         result.add(i);         if (i != 5) {             result.add(10 / i);         }     } } 

Using lambda:

List<Integer> result = IntStream.rangeClosed(1, 10)                                 .boxed()                                 .filter(i -> 10 % i == 0)                                 // a map or forEach function here?                                 // .map(return 10 / i -> if i != 5)                                 .collect(Collectors.toList()); 
like image 654
moon Avatar asked Jul 25 '15 17:07

moon


People also ask

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.

How do I write if else using Java 8?

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

What is lambda expression in Java 8 with example?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.


1 Answers

The essential observation here is that your problem involves a non-isomorphic transformation: a single input element may map to zero, one, or two output elements. Whenever you notice this, you should immediately start looking for a solution which involves flatMap instead of map because that's the only way to achieve such a general transformation. In your particular case you can first apply filter for a one-to-zero element mapping, then flatMap for one-to-two mapping:

List<Integer> result =     IntStream.rangeClosed(1, 10)              .filter(i -> 10 % i == 0)              .flatMap(i -> i == 5 ? IntStream.of(i) : IntStream.of(i, 10 / i))              .boxed()              .collect(toList()); 

(assuming import static java.util.stream.Collectors.toList)

like image 133
Marko Topolnik Avatar answered Sep 29 '22 12:09

Marko Topolnik