本文介紹了將對象列表轉(zhuǎn)換為 Map的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在嘗試將玩家列表轉(zhuǎn)換為地圖.播放器包含名稱和作為變量運行.
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));
我的問題是我試圖通過使用流組合運行而不是通過來轉(zhuǎn)換為地圖.
my problem is i'm trying to convert to map by combining the runs using streams and not getting through.
對每個都進(jìn)行了嘗試并合并了值,如下所示,并獲得了預(yù)期的結(jié)果.
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());
});
結(jié)果將是 {Dhoni=9292, Jaddu=5798, Virat=17904},正在尋找使用流的解決方案.
result would be {Dhoni=9292, Jaddu=5798, Virat=17904}, looking for a solution using streams.
推薦答案
你可以使用toMap
Collector作為:
You can use toMap
Collector as:
Map<String, Integer> mapVal = playerList.stream()
.collect(Collectors.toMap(Player::getName,
Player::getDistance, Integer::sum));
或groupingBy
為:
Map<String, Integer> mapVal = playerList.stream()
.collect(Collectors.groupingBy(Player::getName,
Collectors.summingInt(Player::getDistance)));
這篇關(guān)于將對象列表轉(zhuǎn)換為 Map的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!