Search code examples
javadictionaryjava-streamreducecollect

How to reduce an ArrayList of objects to Map<String,List<String>>


public class Cont {
    public String getContinent() {
        return continent;
    }

    public void setContinent(String continent) {
        this.continent = continent;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public Cont(String continent, String country) {
        super();
        this.continent = continent;
        this.country = country;
    }

    String continent;
    String country;
}

In Main:

ArrayList<Cont> cList = new ArrayList<Cont>();
cList.add(new Cont("Asia", "China"));
cList.add(new Cont("Asia", "India"));
cList.add(new Cont("Europe", "Germany"));
cList.add(new Cont("Europe", "France"));
cList.add(new Cont("Africa", "Ghana"));
cList.add(new Cont("Africa", "Egypt"));
cList.add(new Cont("South America", "Chile"));

Using Java streams, how can I get a Map<String,List<String>> with the following values:

{South America=[Chile], Asia=[China, India], Europe=[Germany, France], Africa=[Ghana, Egypt]}

Solution

  • You can do this

             var map = cList.stream()
                .collect(
                        Collectors.toMap(
                                p -> p.getContinent(),
                                p -> List.of(p.getCountry()),
                                (v1, v2) -> { 
                                    // merge collusion function
                                    var list = new ArrayList<String>();
                                    list.addAll(v1);
                                    list.addAll(v2);
                                    return list;
                                }));
    System.out.println("map" + map.toString());