2

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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Save Soil
  • 75
  • 7
  • Note: if you want to find which teams belong to a *particular* league, then you could simply use `list.stream().filter(team -> Objects.equals(team.getLeague(), yourParticularLeague)).map(FootBallTeam::getName).toList()`. – MC Emperor Aug 08 '22 at 13:10

2 Answers2

3

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())
    ));
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
  • can you please explain how this will work `Collectors.mapping(FootBallTeam::getName,Collectors.toList())` – Save Soil Aug 08 '22 at 12:19
  • @SaveSoil The first argument of `mapping` is a *function* that transforms the stream element (method reference `FootBallTeam::getName` implies that we need to extract a name from the `FootBallTeam` object). The second argument is a *downstream collector*, which describes how these transformed objects should be accumulated. – Alexander Ivanchenko Aug 08 '22 at 12:21
1

Use Collectors.mapping:

Map<String, List<String>> total = footBallTeamList
                .stream()
                .collect(Collectors.groupingBy(
                        FootBallTeam::getLeague,
                        Collectors.mapping(FootBallTeam::getName, Collectors.toList())));;
Nemanja
  • 3,295
  • 11
  • 15