简体   繁体   中英

How can I group values of List in Java using Lambda like we do in python

I want to group values of a map based on the key. Let's say

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);

I want to group values in the map based on the keys: Output should be ["A","B","C"]:[2,3], ["D","B","C"]:[1]

So what I have done:

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());
}

But it doesn't work out, can anyone help here.

PS: In Python, these things can be done with itertools.groupby or reduce , but i am still don't knoww how to do it perfectly in Java

If I understand well, you want to group the identical key set of the maps you added in the last map associated with the original key.

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())));

From the last map, you get the stream of entries (which is a Stream<Entry<Integer, Map<String, Integer>> ). There you group the entries by the key set of their map's values.

Then you map the values of the resulting map using a downstream collector, which collects the keys of the original entries in a List<Integer> .

Output:

{[A, B, C]=[2, 3], [B, C, D]=[1]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM