group all keys with same values in a hashmap java

http‮.www//:s‬lautturi.com
group all keys with same values in a hashmap java

To group all keys with the same values in a HashMap in Java, you can iterate through the map and use a Map to store the keys with the same value.

Here's an example of how you can do this:

Map<String, Integer> map = new HashMap<>();
map.put("Alice", 1);
map.put("Bob", 2);
map.put("Charlie", 3);
map.put("Dave", 1);
map.put("Eve", 2);

Map<Integer, List<String>> grouped = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    int value = entry.getValue();
    String key = entry.getKey();
    grouped.putIfAbsent(value, new ArrayList<>());
    grouped.get(value).add(key);
}

System.out.println(grouped);

This code will create a Map called grouped that contains the keys from the original map grouped by their values. The output will be:

{1=[Alice, Dave], 2=[Bob, Eve], 3=[Charlie]}

Note that this example uses the putIfAbsent() method and the get() method from the Map interface to add keys to the grouped map and retrieve the list of keys for a given value. These methods are available in Java 8 and later. If you are using an earlier version of Java, you can use the containsKey() method to check if a key is present in the map before adding it.

Created Time:2017-11-01 12:05:04  Author:lautturi