Shail
Shail

Reputation: 901

Grouping Java HashMap keys by their values

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?

Upvotes: 2

Views: 9664

Answers (2)

Saravana
Saravana

Reputation: 12817

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]}

Upvotes: 8

Zhe
Zhe

Reputation: 396

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

Upvotes: 1

Related Questions