You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java Stream将Cont对象的ArrayList转换为Map<String,List<String>>

问题:使用Java Stream将Cont对象列表转换为按大洲分组的国家列表Map

现有如下Cont类:

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;
}

在Main方法中初始化了一个Cont对象的ArrayList:

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

需要将上述列表转换为Map<String, List<String>>结构,其中键为大洲名称,值为对应国家的列表,示例输出如下:

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

解决方案

可以通过Java Stream的Collectors.groupingBy结合Collectors.mapping实现分组转换,完整代码如下:

import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        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"));

        // 转换为目标Map结构
        Map<String, List<String>> continentCountryMap = cList.stream()
                .collect(Collectors.groupingBy(
                        // 按大洲名称作为分组键
                        Cont::getContinent,
                        // 将分组内的Cont对象映射为国家名称,再收集为列表
                        Collectors.mapping(Cont::getCountry, Collectors.toList())
                ));

        // 打印验证结果
        System.out.println(continentCountryMap);
    }
}

代码逻辑说明:

  • cList.stream():将ArrayList转换为Stream流,开启流式操作
  • Collectors.groupingBy(Cont::getContinent, ...):指定以Cont对象的大洲属性作为分组的键
  • Collectors.mapping(Cont::getCountry, Collectors.toList()):将每个分组内的Cont对象转换为对应的国家名称,并把这些名称收集成List,作为Map对应键的值

运行代码后,即可得到符合要求的分组Map结构。


内容的提问来源于stack exchange,提问作者Shishir Sahay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:15:40