Flattening nested list in java [closed]

In the below code snippet how can I print list in flatten way by using java 8 stream API?

public class MainClass {
    public static void main(String[] args) {
        List<Employee> list = new ArrayList<>();
        List<Address> jAddress = new ArrayList<>();
        jAddress.add(new Address("Victory Road 1", 10101));
        jAddress.add(new Address("Victory Road 2", 101011));
        list.add(new Employee("John", 1, jAddress));

        List<Address> aAddress = new ArrayList<>();
        aAddress.add(new Address("Cross road", 40101));
        list.add(new Employee("Alex", 2, aAddress));
    }
}

I want to print the list in the below format.

["Jhon", 1, "victory road 1", 110220]
["Jhon", 1, "victory road 2", 101011]
["Alex", 2, "Cross road", 40101]

Answer

It seems that a raw list/array needs to be created including fields from Employee and Address (assuming appropriate getters exist in these classes):

List<List<Object>> flattened = list.stream()
    .flatMap(emp -> emp.getAddresses().stream()
        .map(addr -> Arrays.asList(
            emp.getName(), emp.getId(), 
            addr.getAddress(), addr.getPostalCode()
        ))
    )
    .collect(Collectors.toList());

flattened.forEach(System.out::println); // should print desired result

Leave a Reply

Your email address will not be published. Required fields are marked *