java 8 Lambda expression

0

Good, can someone explain in detail what makes this expression in particular?

listModels.addAll(listaDao.stream().map(this::personEntityToPersonModel).collect(Collectors.toList()));

I have the method:

 private PersonModel personEntityToPersonModel(PersonEntity personEntity){
//codigo...
}

I know what it does but not how it does I would like to understand it because for example when referencing the method is not happening any parameters apparently, thank you very much :) I'm a little fish in java 8

    
asked by xutto 11.10.2017 в 16:54
source

2 answers

1

In the question What does it mean :: in java? it explains what they mean the :: .

Basically, in java 8 now the methods can be sent as parameters. The object listaDao is of type Iterable<PersonEntity> . The method map iterates over each element of the object listadoDao to convert them to type PersonModel .

The subject of the method map in this case is PersonModel map(Function<PersonEntity> p) and as dictates the use of lambdas, to be able to send a method as a parameter, this method must have the same subject and the method personEntityToPersonModel satisfies that condition.

In summary, the method personEntityToPersonModel will be executed for each element that has iterator listaDao . That code can be translated with lambdas in the following way:

listModels.addAll(listaDao.stream().map(personEntity->{

  // codigo del metodo personEntityToPersonModel

}).collect(Collectors.toList()));

And it would work in the same way. The only thing that in your case is sent the method as a parameter instead of defining a lambda.

And finally .collect(Collectors.toList()) convert the resulting Stream to List<PersonModel> .

    
answered by 11.10.2017 / 17:11
source
0

Explanation step by step:

listModels.addAll( //añade a la lista todos los elementos que estén en
                   // la lista que recibe como parámetro
   listaDao.stream() //convierte listaDao en un stream de objetos 
     .map( //transforma el stream de PersonEntity a un stream de PersonModel...
        this::personEntityToPersonModel //...aplicando a cada elemento este método
      ).collect(Collectors.toList()) //y guarda el stream resultante en una lista
);
    
answered by 11.10.2017 в 17:09