Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

java map get key from value

import java.util.HashMap;
import java.util.Map;
 
class Main
{
    public static <K, V> K getKey(Map<K, V> map, V value)
    {
        return map.entrySet().stream()
                .filter(entry -> value.equals(entry.getValue()))
                .findFirst().map(Map.Entry::getKey)
                .orElse(null);
    }
 
    public static void main(String[] args)
    {
        Map<String, Integer> hashMap = new HashMap();
        hashMap.put("A", 1);
        hashMap.put("B", 2);
        hashMap.put("C", 3);
 
        System.out.println(getKey(hashMap, 2));        // prints `B`
    }
}
Source by www.techiedelight.com #
 
PREVIOUS NEXT
Tagged: #java #map #key
ADD COMMENT
Topic
Name
1+5 =