Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: modify specific element in the stream by using lambda expressions

I need to modify a list on int as it follows:

  • Every element == 10 needs to be doubled

Here is my attempt:

list.stream()
            .filter(val -> val.getValue() == 10)
            .map(val -> {
                val.doubleValue();
                return val;
            })
            .forEach(System.out::println);

The problem is that I'm filtering the elements, while I would like to keep them all and just modify the ones == 0.

EDIT: the list is composed of elements of MyType, defined as it follows:

public class MyType {

    private int val;

    public MyType(int v){
        this.val = v;
    }

    public void doubleVal(){
        val*val;
    }

    public int getValue(){
        return val;
    }
}

Any suggestion?

like image 873
Andi Pavllo Avatar asked Dec 10 '22 12:12

Andi Pavllo


2 Answers

Don't use filter. Put all the logic in map :

list.stream()
    .map(val -> val == 10 ? 2*val : val)
    .forEach(System.out::println);

EDIT : I simplified the code after your clarification that the elements of the list are Integers. Note that the original List remains unchanged.

like image 148
Eran Avatar answered Jun 02 '23 01:06

Eran


Assuming that your list is a list of Val, and Val is something like

class Val {
  private int v;

  public Val(int v) {
    this.v = v;
  }
  int getValue() {
    return v;
  }

  public void doubleValue() {
    v *= 2;
  }
}

then

  public static void main(String ... args ) {
        List<Val> ints = Arrays.asList(new Val(1), new Val(5), new Val(10), new Val(2));
        ints.stream().map((v) -> {
            if (v.getValue() == 10) v.doubleValue(); return v;
        }).forEach(v -> System.out.println(v.getValue()));

    }

will do the trick.

like image 34
Redlab Avatar answered Jun 02 '23 01:06

Redlab