Ricky
Ricky

Reputation: 2750

How to multiply array elements by condition

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.

Upvotes: 1

Views: 571

Answers (3)

Amongalen
Amongalen

Reputation: 3131

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.

Upvotes: 2

ifelse.codes
ifelse.codes

Reputation: 2389

You can do this. You don't need a filter , you are mapping with a condition.

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

Upvotes: 3

Eran
Eran

Reputation: 393791

You can combine the filter and map steps:

list.stream()
    .map(n -> n > 9 ? n * 2 : n * 3)
    .forEach(System.out::println);

Upvotes: 6

Related Questions