[英]How can I group values of List in Java using Lambda like we do in python
我想基於鍵對地圖的值進行分組。 比方說
Map<String,Integer> map1 = new TreeMap<String,Integer>();
map1.put("D", 3);
map1.put("B", 2);
map1.put("C", 1);
Map<String,Integer> map2 = new TreeMap<String,Integer>();
map2.put("A", 13);
map2.put("B", 22);
map2.put("C", 12);
Map<String,Integer> map3 = new TreeMap<String,Integer>();
map3.put("A", 33);
map3.put("B", 32);
map3.put("C", 32);
Map<Integer,Map<String,Integer>> map = new HashMap <Integer,Map<String,Integer>>();
map.put(1,map1);
map.put( 2, map2);
map.put(3, map3);
System.out.println(map);
我想根據鍵對映射中的值進行分組:輸出應為["A","B","C"]:[2,3], ["D","B","C"]:[1]
所以我做了什么:
Map<List<String>, List<Integer>> newMap = new HashMap<List<String>, List<Integer>>();
for (Integer item : map) {
Map<String,Integer> currentValue = map.get(item);
List<String> oldItemKeySet = newMap.get(currentValue.keySet());
newMap.put(currentValue.keySet(), (oldItemKeySet == null) ? 1 : oldItemKeySet.put());
}
但這行不通,任何人都可以在這里提供幫助。
PS:在Python中,這些事情可以通過itertools.groupby
或reduce
來完成,但是我仍然不知道如何在Java中完美地做到這一點。
據我所知,您希望將在與原始鍵關聯的最后一個映射中添加的映射的相同鍵集進行分組。
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
...
Map<Set<String>, List<Integer>> newMap =
map.entrySet()
.stream()
.collect(groupingBy(e -> e.getValue().keySet(),
mapping(Map.Entry::getKey, toList())));
從最后一個映射中,獲得條目流(它是Stream<Entry<Integer, Map<String, Integer>>
)。 在那里,您可以根據地圖值的鍵集對條目進行分組。
然后,使用下游收集器映射結果映射的值,該收集器將原始條目的鍵收集在List<Integer>
。
輸出:
{[A, B, C]=[2, 3], [B, C, D]=[1]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.