Search code examples
collectionsjava-8grouping

Group the list of Objects and convert to a map using java8


`Hi,

I have a list of Employees employeeList (assume this list has some values present)

List<Employee> employeeList ;

Say, My Employee DTO is something like below :

Employee {
List<Book> bookList;
}

Book DTO:

Book {
private String bookId;
private String bookName;
}

I have to stream through the employeeList and group the employees with same book Id and convert to a map having key as the BookId and value as list of Employees. I want to achieve this using java8 concepts. Please help!

I tried to use Collectors.groupingBy but I have to traverse through another List of Books inside list of Employees. Could not figure out how?`


Solution

  • You can flatten the Employee list to pairs of Employee, Book ID and then collect to the Map you want.

    Something like this (not tested):

    Map<String,List<Employee>> map =
        employeeList.stream()
                    .flatMap(e -> e.getBookList()
                                   .stream()
                                   .map(book -> new SimpleEntry<String,Employee>(book.getID (), e)))
                    .collect (Collectors.groupingBy (Map.Entry::getKey,
                                                     Collectors.mapping(Map.Entry::getValue,
                                                                        Collectors.toList())));