Map Interface in Java | PLM Developer

In Java, the Map is an interface that doesn't extend the Collection interface. The map interface allows storing elements as key-value pairs. The Map doesn't allow duplicates keys and values may have a duplicate. We cannot traverse the elements in the Map, so we need to convert it into Set using keySet() or entrySet() method.
The Map is an interface, so we cannot provide a direct implementation of it. We can use the following classes to implement the functionalities of Map.

  1. HashMap
  2. LinkedHashMap
  3. TreeMap
  4. WeakHashMap
  5. EnumMap

The Map is present in Java.util package, we must import Java .util.Map before using it.

Map<Key, Value> map= HashMap<>();
Map<Key, Value> map= LinkedHashMap<>();
Map<Key, Value> map= TreeMap<>();



HashMap implementation of Map retriving values using keySet:

import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

public class HashMapImpl {

    public static void main(String[] args) {
        //Create Map with HashMap class
        Map<Integer, String> map = new HashMap<>();

        //Adding elements to HashMap
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");
        map.put(4, "Four");
        map.put(2, "Two");

 //Converting Map to Set 
        Set set=map.entrySet();
        Iterator itr=set.iterator();  
        while(itr.hasNext()){  
            //Converting to Map.Entry so that we can access key and values separately
            Map.Entry entry=(Map.Entry)itr.next();  
            System.out.println(entry.getKey()+" "+entry.getValue());  
        }  
    }
}

output:
1 One
2 Two
3 Three
4 Four

Form the above program and output; You can see we tried to add a new value with a duplicate key (2) HashMap removed the duplicate element. We converted the Map into Set and retrieved the elements using keySet through Iterator. 



HashMap implementation of Map retriving values using entrySet:


import java.util.Set;
import java.util.Map;
import java.util.HashMap;

public class HashMapImpl {

    public static void main(String[] args) {
        //Create Map with HashMap class
        Map<Integer, String> map = new HashMap<>();

        //Adding elements to HashMap
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");
        map.put(4, "Four");


        // Converting Map to Set using entrySet
       Set< Map.Entry<Integer, String> > set = map.entrySet();    
  
       //Iterating using foreach loop
       for (Map.Entry<Integer, String> obj:set) 
       { 
           System.out.println(obj.getKey()+":"+(obj.getValue())); 
       } 
    }
}

output:
1:One
2:Two
3:Three
4:Four

Form the above program and output; We converted the Map into Set and retrieved the elements using entrySet through the foreach loop.

Post a Comment

0 Comments