Map in Java

A Map is an interface in Java. Implementations of the Map interface are collections that store key and value pairs. Each key is linked to a specific value. 

A Map can only contain unique keys, no duplicates. If we try to add an existing key, the existing one will be replaced with a new one.

Most used implementations of the Map interface:

  • HashMap
  • LinkedHashMap
  • TreeMap

What is a HashMap in Java?

HashMap class implements a Map interface, which does not guarantee the order of keys and values.
This means it does not return the keys and values in the same order in which they have been inserted into the HashMap.

How to create a HashMap in Java?

We create a new HashMap object by instantiating it like any other object in Java.

 HashMap<K, V> map = new HashMap<>();

Between the <> brackets, we specify which type of elements the map will contain. K stands for Key, and V stands for Value.

Or using polymorphism.
The variable that holds the address of the new object will be of type Map.
This is possible because HashMap implements the Map interface.

 Map<Integer, String> map = new HashMap<>();

How to add elements to HashMap in Java?

We add elements to the map using the put(Object key, Object value) method.
Example:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
        
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
       
    System.out.println(map);
  }
}
Output: {1=Java, 3=Kotlin, 7=Python, 10=Ruby}

Pay attention to the output, the keys that are printed are not in any order, not even in the order of insertion into the map.

Using the putAll() method, we can add all the elements of an existing map to the newly created map.

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    Map<Integer, String> map2 = new HashMap<>();
    
    map2.putAll(map);
        
    System.out.println(map2);
  }
}
Output: {1=Java, 10=Ruby, 3=Kotlin, 7=Python}

How to remove elements from HashMap?

When we want to remove one whole entry (Key-Value pair) from the map, we use the remove(Object key) method and pass the corresponding key as a parameter.
Example:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    map.remove(10);
        
    System.out.println(map);
  }
}
Output: {1=Java, 3=Kotlin, 7=Python}
 
We can also remove all elements from the map using the clear() method.

Example:
class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    map.clear();
        
    System.out.println(map);
  }
}
Output: {}

How to replace elements in HashMap?

Using the replace(Object key, Object value) method, we can replace the Key-Value pair by passing a key and a value to replace the existing value associated with the supplied key.
Example:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    map.replace(7, "JavaScript");
        
    System.out.println(map);
  }
}
Output: {1=Java, 3=Kotlin, 7=JavaScript, 10=Ruby}


How to access HashMap elements?

In the HashMap, we retrieve the value by the corresponding key by using the get(Object key) method.
Example:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    System.out.println(map.get(1));
  }
}
Output: Java

If we pass a key that does not exist in the map, we get null as the output.

How to get the size of the HashMap in Java?

To find out the size of the HashMap in Java, we use the size() method.
Example:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
        
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    System.out.println("Size of the map: " + map.size());
  }
}
Output: Size of the map: 4

What is a LinkedHashMap in Java?

LinkedHashMap class inherits the HashMap class and implements the Map interface.
The insertion order is guaranteed here.

Example:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new LinkedHashMap<>();
        
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    System.out.println(map);
  }
}
Output: {1=Java, 7=Python, 10=Ruby, 3=Kotlin}

See how the elements are printed in the same order as they were inserted.

What is a TreeMap in Java?

TreeMap class maintains ascending order. It implements the NavigableMap interface and extends AbstractMap class.

Example:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new TreeMap<>();
    
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    System.out.println(map);
  }
}
Output: {1=Java, 3=Kotlin, 7=Python, 10=Ruby}

Here, in the output, we see that the elements are sorted by key, in ascending order.

How to iterate over Map in Java?

We can iterate through map elements in several ways.

Using for-each loop:

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
  
  }
}
Output: Key = 1, Value = Java Key = 3, Value = Kotlin Key = 7, Value = Python Key = 10, Value = Ruby

Here, we used the entrySet() method that returns a collection-view (Set<Map.Entry<K, V>>) of the mappings contained in this map. And we used entry.getKey() to retrieve the key and entry.getValue() to retrieve the value of the current iteration.

Using Iterator

We can use the Iterator interface to iterate over the map.

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    Iterator<Map.Entry<Integer, String>> itr = map.entrySet().iterator();
    
    while (itr.hasNext()) {
      Map.Entry<Integer, String> entry = itr.next();
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
  
  }
}
Output: Key = 1, Value = Java Key = 3, Value = Kotlin Key = 7, Value = Python Key = 10, Value = Ruby

Using Java 8 forEach method

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
       
    map.forEach((k, v) -> System.out.println("Key = " + k + ", Value = " + v));
  }
}
Output: Key = 1, Value = Java Key = 3, Value = Kotlin Key = 7, Value = Python Key = 10, Value = Ruby
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *