Collectors.groupingBy - collecting to list of some property of Object instead of list of Object itself

Viewed 119

Lets say I have a class

public class FootBallTeam {
    private String name; // team name
    private String league;

    //getters, setters, etc.
}

I'm trying to group Teams names according to their League.
For example:

League A -> [nameOfTeam2, nameOfTeam5]
League B -> [nameOfTeam1, nameOfTeam3, nameOfTeam4]

With below code I am getting Map<String, List<FootBallTeam>> which is pointing to list of team objects List<FootBallTeam>.

Map<String, List<FootBallTeam>> teamsGroupedByLeague = list
    .stream()
    .collect(Collectors.groupingBy(FootBallTeam::getLeague));

Instead I just want the names of FootBallTeams i.e. FootBallTeam.name.
In other words Map<String, List<String>> where List<String> holds teams names .

How to achieve that?

2 Answers

I just want the names of FootTeams i.e. FootBallTeam.name

You need to apply additional collector mapping() as a downstream collector of groupingBy()

Map<String, List<String>> teamNamesByLeague = list.stream()
    .collect(Collectors.groupingBy(
        FootBallTeam::getLeague,
        Collectors.mapping(FootBallTeam::getName,
            Collectors.toList())
    ));

Use Collectors.mapping:

Map<String, List<String>> total = footBallTeamList
                .stream()
                .collect(Collectors.groupingBy(
                        FootBallTeam::getLeague,
                        Collectors.mapping(FootBallTeam::getName, Collectors.toList())));;
Related