【问题标题】:Java Stream convert List into MapJava Stream 将 List 转换为 Map
【发布时间】:2021-11-11 15:45:27
【问题描述】:

我有一堂课PlayerAndCountry

class PlayerAndCountry {
    private Country country;
    private Player player;
}

还有一个List<PlayerAndCountry>

我想要这样的最终地图:Map<Country,List<Player>>

我知道如何获取Map<Country, List<PlayerAndCountry>>,但不知道Map<Country,List<Player>>

【问题讨论】:

  • list.stream().collect(groupingBy(PlayerAndCountry::getCountry, mapping(PlayerAndCountry::getPlayer, toList()))); 这里,Collectors 是静态导入:import static java.util.stream.Collectors.*;

标签: java java-8 java-stream


【解决方案1】:

你需要使用Collectors.mapping来实现它:

Map<Country, List<Player>> collect = list.stream()
        .collect(Collectors.groupingBy(PlayerAndCountry::getCountry,
                Collectors.mapping(PlayerAndCountry::getPlayer, Collectors.toList()))
        );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多