Java - How to find key by value in HashMap

How to find key by value in HashMap.

1. keySet()

keySet() returns all keys in HashMap as a Set. You can find keys by fetching a value as a key and comparing it with the value you want to find.

import java.util.HashMap;
import java.util.Map;

public class GetKeyFromValueInHashMap {

    public static void main(String[] args) {

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

        for (String key : map.keySet()) {
            Integer value = map.get(key);
            System.out.println("Iterating, key: " + key);

            if (value == 2) {
                System.out.println("key of the value 2: " + key);
            }
        }
    }
}

Output:

Iterating, key: banana
key of the value 2: banana
Iterating, key: apple
Iterating, key: kiwi
Iterating, key: melon
key of the value 2: melon

2. entrySet()

entrySet() returns Entry for Key and Value. You can find the keys you want by comparing values in the same way as above.

import java.util.HashMap;
import java.util.Map;

public class GetKeyFromValueInHashMap2 {

    public static void main(String[] args) {

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

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String key = entry.getKey();
            Integer value = entry.getValue();
            System.out.println("Iterating, key: " + key + ", value: " + value);

            if (value == 2) {
                System.out.println("key of the value 2: " + key);
            }
        }
    }
}

Output:

Iterating, key: banana, value: 2
key of the value 2: banana
Iterating, key: apple, value: 1
Iterating, key: kiwi, value: 3
Iterating, key: melon, value: 2
key of the value 2: melon

3. Stream

You can compare values using Stream and return the key for the matching value as a Set.

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class GetKeyFromValueInHashMap3 {

    public static void main(String[] args) {

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

        Set<String> foundKeys = map.entrySet()
                                   .stream()
                                   .filter(entry -> Objects.equals(entry.getValue(), 2))
                                   .map(Map.Entry::getKey)
                                   .collect(Collectors.toSet());

        System.out.println("Result: " + foundKeys);
    }
}

Output:

Result: [banana, melon]
codechachaCopyright ©2019 codechacha