Java Stream 将 List 转换为 Map

Java Stream convert List into Map

我有一个 class PlayerAndCountry :

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

还有一个List<PlayerAndCountry>

我希望我的最终地图是这样的:Map<Country,List<Player>>

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

需要使用Collectors.mapping来实现:

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