Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Collector groupingby not to return entire Object

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}

=============

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
    ));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading