如何将对象的ArrayList减少到Map<String,List<String>> [重复]

问题描述 投票:0回答:1
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;
}

主要:

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"));

使用 Java 流,如何获得具有以下值的

Map<String,List<String>>

{South America=[Chile], Asia=[China, India], Europe=[Germany, France], Africa=[Ghana, Egypt]}
java dictionary java-stream reduce collect
1个回答
-1
投票

你可以这样做

         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());
© www.soinside.com 2019 - 2024. All rights reserved.