0

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

Raider
  • 394
  • 1
  • 2
  • 26

2 Answers2

0

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()));
gilad a
  • 39
  • 3
-1

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)));
Felix Ng
  • 612
  • 5
  • 4
  • While this code may answer the question, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Apr 05 '16 at 11:46