Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten list in java 8

class Employee {
    private String name;
    private List<Employee> members;
}

List<Employee> emps = Arrays.asList(new Employee("A", Arrays.asList(
     new Employee("B", null),
     new Employee("C", null)
)))

The code to flatten the List:

List<Employee> total = 
    emps.stream()
        .flatMap(emp -> emp.members.stream())
        .collect(Collectors.toList());

The total List should have 3 elements, but it only has 2.

like image 476
Sandeep Tiwari Avatar asked Dec 31 '22 01:12

Sandeep Tiwari


1 Answers

Eran's answer is wrong, there is no concat on Stream instance. This should work:

emps.stream()
        .flatMap(emp -> Stream.concat(emp.members.stream(), Stream.of(emp)))
        .collect(Collectors.toList());

Stream#concat

like image 135
Aniket Sahrawat Avatar answered Jan 12 '23 11:01

Aniket Sahrawat