本文介紹了將對象列表轉換為 Map的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試將玩家列表轉換為地圖.播放器包含名稱和作為變量運行.
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());
});
結果將是 {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)));
這篇關于將對象列表轉換為 Map的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!