JAVA HashMap get keys by values

https:‮al.www//‬utturi.com
JAVA HashMap get keys by values

To get the keys of a HashMap in Java by their corresponding values, you can use the entrySet method of the HashMap class and a loop.

Here is an example of how to get the keys of a HashMap by their values:

HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

int valueToFind = 2;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    if (entry.getValue().equals(valueToFind)) {
        String key = entry.getKey();
        System.out.println(key);
    }
}

In this example, the map variable is a HashMap object that maps strings to integers. The entrySet method returns a Set of the entries in the map, which are represented by Map.Entry objects.

You can use a for loop to iterate over the entries in the Set. The entry variable is an instance of Map.Entry, and you can use the getKey and getValue methods to get the key and value of the entry.

If the value of the entry equals the value you are looking for (in this case, 2), you can print the key.

Note that this approach will only find the first key that corresponds to the specified value. If there are multiple keys with the same value, you will need to modify the code to handle this case.

For example, you could use a List to store all the keys with the specified value, and then return the list at the end of the loop:

List<String> keys = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    if (entry.getValue().equals(valueToFind)) {
        keys.add(entry.getKey());
    }
}
return keys;

You can also use the values method of the HashMap class to get a collection of the values in the map, and use the contains method to check if the collection contains the value you are looking for.

For example:

Collection<Integer> values = map.values();
if (values.contains(valueToFind)) {
    // the value is present in the map
}

This approach is faster than the first one, but it only works if the value you are looking for is unique in the map. If there are multiple keys with the same value, you will need to use the first approach to get all the keys with the specified value.

Created Time:2017-11-03 22:21:02  Author:lautturi