Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace nested loops with Java 8 streams

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]

like image 897
Pons Avatar asked Jan 04 '23 11:01

Pons


1 Answers

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());
like image 181
shmosel Avatar answered Jan 11 '23 11:01

shmosel