javajava-stream

Create a list of data carriers with java Streams


I want to convert a list of nested objects into a flat list using Java streams. For this reason, a list of companies is first drawn up with employees:

 // create Apple Employees
        List<Employee> appleEmployees = List.of(
                new Employee("John", "Doe"), new Employee("Joe", "Bloggs")
        );
        Company apple = new Company("Apple", appleEmployees);


        // create Microsoft Employees
        List<Employee> microsoftEmployees = List.of(
                new Employee("John", "Public"), new Employee("Harry", "Fortune")
        );
        Company microsoft = new Company("Microsofr", microsoftEmployees);


        // put apple and microsft in a list
        List<Company> companies = List.of(apple, microsoft);

        // data carrier
        record CompanyData(String companyName,String employeeName, String employeeSurname) {}

What do I have to do now if I use Java Streams:

// How to stream this?
        List<CompanyData> companyData = companies.stream().????

We should have a list of 4 CompanyData objects at the end of the stream, which contains the name of the company and the first and last name of the employee, something like this:

  List<CompanyData> companyData = List.of(
            new CompanyData("Apple", "John", "Doe"),
            new CompanyData("Apple", "Joe", "Bloggs"),
            new CompanyData("Microsoft", "John", "Public"),
            new CompanyData("Microsoft", "Harry", "Fortune")
    );

Is this even possible and should Java streams be used for the case?


Solution

  • You can use flatMap:

    List<CompanyData> companyData = companies.stream().flatMap(company ->
        company.getEmployees().stream().map(employee -> 
            new CompanyData(company.getName(), employee.getName(), employee.getSurname())
        )).toList();