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

如何用Java Stream将List<PlayerAndCountry>转为Map<Country,List<Player>>

实现方案

你可以通过Collectors.groupingBy搭配下游的Collectors.mapping收集器完成转换,实现步骤如下:

  1. 首先为PlayerAndCountry类补充私有字段的getter方法(用反射也可获取字段值,但规范写法用getter兼容性和安全性更好):
class PlayerAndCountry {
    private Country country;
    private Player player;

    public Country getCountry() {
        return country;
    }

    public Player getPlayer() {
        return player;
    }
}
  1. 编写Stream处理逻辑:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 你的原始集合
List<PlayerAndCountry> sourceList = ...;

Map<Country, List<Player>> resultMap = sourceList.stream()
        .collect(Collectors.groupingBy(
                // 分组key:取Country字段
                PlayerAndCountry::getCountry,
                // 下游收集器:把分组内的每个元素映射为Player,再收集为List
                Collectors.mapping(PlayerAndCountry::getPlayer, Collectors.toList())
        ));

如果你使用Java 16及更高版本,也可以用toMap方法实现同等效果:

Map<Country, List<Player>> resultMap = sourceList.stream()
        .collect(Collectors.toMap(
                PlayerAndCountry::getCountry,
                pac -> new ArrayList<>(List.of(pac.getPlayer())),
                (existingList, newList) -> {
                    existingList.addAll(newList);
                    return existingList;
                }
        ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:36:05