Converting a list of objects to Map

[亡魂溺海] 提交于 2021-02-04 21:11:36

问题


I'm trying to convert a list of players into map. player contains name & runs as variables.

List<Player> runnerList = Arrays.asList(new Player("Virat", 4654), new Player("Jaddu", 5798),
            new Player("Dhoni", 4581), new Player("Virat", 8709), new Player("Dhoni", 4711),
            new Player("Virat", 4541));

my problem is i'm trying to convert to map by combining the runs using streams and not getting through.

Tried for each and merged the values, like below, and getting expected result.

playerList.forEach(n -> {
            mapVal.merge((n.getName()), (n.getDistance()), (val1, val2) -> IntStream.of(val1, val2).sum());
        });

result would be {Dhoni=9292, Jaddu=5798, Virat=17904}, looking for a solution using streams.


回答1:


You can use toMap Collector as:

Map<String, Integer> mapVal = playerList.stream()
        .collect(Collectors.toMap(Player::getName,
                Player::getDistance, Integer::sum));

or groupingBy as:

Map<String, Integer> mapVal = playerList.stream()
        .collect(Collectors.groupingBy(Player::getName,
                Collectors.summingInt(Player::getDistance)));


来源:https://stackoverflow.com/questions/58953994/converting-a-list-of-objects-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!