How to multiply array elements by condition

Ricky :

I have a array and want to multiply the elements greater than 9 by 2 and lesser than or equal to 9 by 3.

  List<Integer> list = Arrays.asList(3, 6, 9, 12, 15);
  list.stream().map(number -> number * 3).forEach(System.out::println); 

This one multiplies everything by 3 , where

list.stream().filter(number -> number>3).map(number -> number * 3).forEach(System.out::println);

this one multiplies but also filters.

I want 3 ,6 ,9 multiplied by 3 and 12, 15 multiplied by 2.

Any help is appreciated.

Amongalen :

In case someone don't like the ternary operator in Eran's answer, you could use a block instead, like this:

list.stream()
  .map(n -> {
     if (n > 9){ 
        return n * 2; 
      }
      else { 
        return n * 3; 
      }
    })
  .forEach(System.out::println);

I think the solution with ternary operator is cleaner in this specific case but this is an option as well. It might be useful if there are more conditions.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418382&siteId=1