Answers for "how to get key from map by value in java"

0

JAVA HashMap get keys by values

Map<String, String> map = new HashMap<String, String>();
    
    map.put("abc", "123");
    map.put("xyz", "456");
    
    for(Entry<String, String> entry : map.entrySet()) {
        if(entry.getValue().equalsIgnoreCase("456")) {
            System.out.println(entry.getKey());
        }
    }
Posted by: Guest on September-12-2021
0

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`
    }
}
Posted by: Guest on June-07-2022

Code answers related to "how to get key from map by value in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language