You can query a HashMap in Java with entrySet(), keySet() and values() methods to get all keys and values mapping; get methods to return value by the specified key; containsKey and containsValue methods to check existing; size and isEmpty methods to check the HashMap size

Get all HashMap keys and values

  • Set<Map.Entry<K, V>> entrySet() method gets all key-value mappings entries contained in the map
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
immutableMap.entrySet().forEach(System.out::println);
  • Set<K> keySet() method gets all keys contained in the map
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
immutableMap.keySet().forEach(System.out::println);
  • Collection<V> values() method gets all values contained in the map
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
immutableMap.values().forEach(System.out::println);


Get value by the specified key

  • V get(Object key) method gets the value mapped to the key argument

    The returned value may be null if the key is mapped to null or there is no mapping value to it

Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

map.get("k1"); // 1  
map.get("k2"); // null  
map.get("k3"); // null  
map.get(null); // null
  • Java 8+ V getOrDefault(Object key, V defaultValue) method gets the value mapped to the key argument or defaultValue if there is no mappings for the key
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

map.get("k1", 0); // 1  
map.get("k3", 0); // 0


Check if key or value existing

  • boolean containsKey(Object key) method checks if a map contains a mapping for the specified key
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

System.out.println(map.containsKey("k1")); // true  
System.out.println(map.containsKey("k3")); // false  
  • boolean containsValue(Object value) method checks if a map contains a mapping for the specified value
Map<String, Integer> map = new HashMap<>();  
map.put("k1", 1);  
map.put("k2", null);

System.out.println(map.containsValue(1)); // true  
System.out.println(map.containsValue(2)); // false  


Check HashMap size

  • int size() gets the number of key-value mappings in a map, O(1)
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
map.size(); // 2
  • boolean isEmpty() checks if a map contains no key-value mappings, O(1)
Map<String, Integer> immutableMap = Map.of("k1", 1, "k2", 2);  
map.isEmpty(); // false