Pons Pons -4 years ago 160
Java Question

Java 8 - Nested loops

I want to use Java 8 stream for the below implementation. Basically i want to parse one list and form another list of different objects.

Input - list of Person pojos,
Output - list of PersonInfo pojos

List<Person> persons = new ArrayList<Person>();

Person max = new Person();
max.setName("Max");
max.setAge(10);
max.addAddress(new Address("Street1", "City1"));
max.addAddress(new Address("Street2", "City2"));

Person peter = new Person();
peter.setName("Peter");
peter.setAge(20);
peter.addAddress(new Address("Street1", "City1"));
peter.addAddress(new Address("Street2", "City2"));

persons.add(max);
persons.add(peter);

System.out.println("Input: " + persons);

List<PersonInfo> personInfos = new ArrayList<PersonInfo>();
PersonInfo personInfo = null;
for (Person person : persons) {
for (Address addr : person.getCurrAndPrevAddrs()) {
personInfo = new PersonInfo();
personInfo.setName(person.getName());
personInfo.setAge(person.getAge());
personInfo.setAddrs(addr);
personInfos.add(personInfo);
}
}

System.out.println("Output: " + personInfos.toString());


sample output:
Input: [Max 10 [Street1 City1, Street2 City2], Peter 20 [Street1 City1, Street2 City2]]

Output: [Max 10 Street1 City1, Max 10 Street2 City2, Peter 20 Street1 City1, Peter 20 Street2 City2]

Answer Source
List<PersonInfo> personInfos = persons.stream().flatMap(person -> person.getCurrAndPrevAddrs().stream().map(addr -> {
        PersonInfo personInfo = new PersonInfo();
        personInfo.setName(person.getName());
        personInfo.setAge(person.getAge());
        personInfo.setAddrs(addr);              
        return personInfo;
})).collect(Collectors.toList());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download