Using lambda expressions in Java

2

I am practicing Lambda expressions and I have the following. I have a person class:

 private static class Persona {
    public int a;
    public String b;


    public Persona(int a,String b){
        this.a=a;
        this.b=b;
    }

    public String toString(){
    return a+","+b;
    }

    public int getA(){
    return a;
    }
   }

I have an ArrayList with the following data:

 ArrayList<Persona> array=new ArrayList<Persona>();
        array.add(new Persona(1,"a"));
        array.add(new Persona(2,"b"));
        array.add(new Persona(3,"c"));

I applied the following map:

  array.stream().map(p->p=new Persona(p.a+1,p.b)).forEach(System.out::println);

The result I get is correct and is:

  

2, a

     

3, b

     

4, c

My question is whether there is any way to add 1 to the attribute a of each person that is in the ArrayList without creating a new Object and printing it in the same way.

Before I tried array.stream().map(p->p.a+1).forEach(System.out::println); but it only prints:

  

2

     

3

     

4

    
asked by FrEqDe 16.05.2017 в 06:06
source

2 answers

5

You can do it with forEach :

//necesitarás crear el setter apropiado
array.stream().forEach(p -> p.setA(p.getA() + 1));

Consider Stream#map is used to generate a new stream based on the transformation applied to each element of the current stream, not to modify the current values of the stream.

    
answered by 16.05.2017 / 06:26
source
0

Hi, you can try the replaceAll method which receives a UnaryOperator:

array.replaceAll( x -> new Persona(x.a+1, x.b) );
array.forEach(System.out::println);

I hope you serve

Greetings.

    
answered by 16.05.2017 в 06:44