Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Java HashMap keys by their values

Tags:

java

hashmap

Suppose I have this HashMap:

(key: value)
A: 3
B: 4
C: 2
D: 4
E: 1
F: 3

and I want to convert it to this HashMap:

1: {"E"}
2: {"C"}
3: {"A", "F"}
4: {"B", "D"}

How do I go about doing this?

like image 927
Shail Avatar asked Sep 21 '26 03:09

Shail


2 Answers

With Java8 streams

Map<Integer, List<String>> valueMap = map.keySet().stream().collect(Collectors.groupingBy(k -> map.get(k)));

Output

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

using method ref

Map<Integer, List<String>> valueMap = map.keySet().stream().collect(Collectors.groupingBy(map::get));

to get the keys is sorted way

Map<Integer, List<String>> valueMap = map.keySet().stream().collect(Collectors.groupingBy(map::get, TreeMap::new, Collectors.toList()));

In Java7 and below

    Map<Integer, List<String>> valuesMap = new HashMap<>();
    for (String key : map.keySet()) {
        Integer val = map.get(key);
        if (valuesMap.get(val) == null) {
            List<String> values = new ArrayList<>();
            values.add(key);
            valuesMap.put(val, values);
        } else {
            valuesMap.get(val).add(key);
        }
    }

output

{1=[E], 2=[C], 3=[A, F], 4=[B, D]}
like image 171
Saravana Avatar answered Sep 22 '26 17:09

Saravana


Instead of a Map of a Collection, consider using a Multimap.

Multimap<Integer, String> multimap = HashBasedMultimap.create()
for (Entry<String, Integer> entry : map.entrySet()) {
  multimap.put(entry.getValue(), entry.getKey());
}
like image 37
Zhe Avatar answered Sep 22 '26 17:09

Zhe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!