Avoid this for loop with Lambdaj

86 Views Asked by At

How can avoid this loop with lambdaj, I want to add all elements from List personas into another list

String tipo = "type_1";
for (Person person : personas) {
    lista.add(new SimpleResultForm(tipo, person));
}

I'm using Java 7 so, Java 8 lambda expresions won't work, I need a solution arround Lambdaj library

2

There are 2 best solutions below

0
gilad a On

With java 8:

String tipo = "type_1";
lista = personas.stream()
             .map(person -> new SimpleResultForm(tipo, person))
             .collect(Collectors.toList());

And in case lista already contains data:

String tipo = "type_1";
lista.addAll(personas.stream()
             .map(person -> new SimpleResultForm(tipo, person))
             .collect(Collectors.toList()));
1
Felix Ng On

In Java 8, assume you had already created the list "lista", then this one-liner should do the work.

String tipo = "type_1";
personas.stream().forEach(e -> lista.add(new SimpleResultForm(tipo, e)));