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

Viewed 3608

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

1 Answers

Use Collectors.mapping:

Map<String, List<Project>> res = results
    .stream()
    .collect(Collectors.groupingBy(
        Detail::getTitle,
        Collectors.mapping(Detail::getProject, Collectors.toList())));
Related