Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Streams group list entries based on a property but collect a property of object in Map

Sorry for the weird title. Basically what I'm trying to do is as follows. I have a class called Details, let's say.

class Detail{
        String title;
        Project project;
}

Using Streams, as you can see I'm able to group Detail by their titles. However I want to group Projects inside of those Detail by title, not Detail.

List<Detail> results; // not empty    
Map<String, List<Detail>> res = results
                    .stream()
                    .collect(groupingBy(Detail::getTitle));

Thanks, beforehand

like image 593
Mansur Avatar asked Sep 11 '18 18:09

Mansur


1 Answers

Use Collectors.mapping:

Map<String, List<Project>> res = results
    .stream()
    .collect(Collectors.groupingBy(
        Detail::getTitle,
        Collectors.mapping(Detail::getProject, Collectors.toList())));
like image 80
fps Avatar answered Oct 27 '22 09:10

fps