问题
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