I have FootTeam object .I am trying to find which teams belongs to Which League.
Expected O/p is
> EPL : { MAN_UTD,MAN_CITY,CHELSEA} BUNDESLIGA : { > BAYERN,DORTMUND,STUTTGART}
=============
public class FootBallTeam {
private String name; //team name
private String league;
Below code works fine but it gives me the complete FootBallTeam object.I just want the name of FootTeams i.e FootBallTeam.name
Map<String, List<FootBallTeam>> total = list
.stream()
.collect(
Collectors.groupingBy(
FootBallTeam::getLeague
));
Sample objetcs in the list. EPL and BBUNDESLIGA are 2 leagues
FootBallTeam f1 = new FootBallTeam("MAN_UTD", "EPL");
FootBallTeam f2= new FootBallTeam("CHELSEA", "EPL");
FootBallTeam f3 = new FootBallTeam("MAN_CITY", "EPL");
FootBallTeam f4 = new FootBallTeam("BAYERN", "BUNDESLIGA");
FootBallTeam f5 = new FootBallTeam("DORTMUND", "BUNDESLIGA");
FootBallTeam f6 = new FootBallTeam("STUTTGART", "BUNDESLIGA")
>Solution :
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())
));