Today met colleagues asked how to be grouped according to a Map value in the group, was my first thought is to value and key exchange,
different key multiple value corresponding to a set of code is as follows:
1
2
Map <String, Integer> = new new SataMap the HashMap <> ();
Final the Map <Integer, List <String >> new new = the groupMap the HashMap <> ();
SataMap.put ( "A",. 1);
SataMap.put ( "B",. 3 );
SataMap.put ( "C", 2);
SataMap.put ( "D",. 4);
SataMap.put ( "E", 2);
SataMap.put ( "F",. 4);
SataMap.put ( "G",. 3);
SataMap.put ( "H", 2);
System.out.println (Result);
SataMap.forEach (new new BiConsumer <String, Integer>() {
@Override
public void accept(String key, Integer value) {
if(groupMap.containsKey(value)){
groupMap.get(value).add(key);
}else{
List<String> values = new ArrayList<>();
values.add(key);
groupMap.put(value, values);
}
}
});
The results quickly beaten face, and my colleagues to find a better way
Map <Integer, List <of Map.Entry <String, Integer >>> SataMap.entrySet Result = () Stream () the collect (Collectors.groupingBy (C -> c.getValue ()));..
. 1
will be converted to Map a collection of entry, and then use a set of packet mode, it is simple to achieve this function