java map get value by key code example

Example 1: find a value in hashmap

if(hashMap.containsKey(key)) {
    Object o = hashMap.get(key);

}

Example 2: java map get the key from value

public static <T, E> Set<T> getKeyByValue(Map<T, E> map, E value) {
    return map.entrySet()
              .stream()
              .filter(entry -> Objects.equals(entry.getValue(), value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}

Example 3: hashmap get value java

//Import Hashmap
import java.util.HashMap;
   
    HashMap<String, String> dir = new HashMap<String, String>();
//Add key, values  
    dir.put("hi", "hello");
	dir.put("wow", "amazing");
//print value for hi.
    System.out.println(dir.get("hi");

Example 4: hashmap get value by key java

import java.util.HashMap;
//Within a class
//You can do new HashMap<Key Type, Value Type>();, but you don't need to
HashMap<Int, String> examplehashmap=new HashMap<>();
{
//put in values
 examplehashmap.put(5, "example");
};
//get value
examplehashmap.get(5);
//returns "example"