• A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.


  • The Map interface includes methods for basic operations (such as put, get, remove, containsKey, containsValue, size, and empty), bulk operations (such as putAll and clear), and collection views (such as keySet, entrySet, and values).


  • The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.


    1. HashMap HashMap is the implementation of Map, but it doesn't maintain any order.


    2. LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.


    3. TreeMap TreeMap is the implementation of Map and SortedMap. It maintains ascending order.


  • Map Interface Basic Operations The basic operations of Map (put, get, containsKey, containsValue, size, and isEmpty) behave exactly like their counterparts in Hashtable.


  •  
    import java.util.*;  
    public class MapExample1 {  
    public static void main(String[] args) {  
        Map map=new HashMap();  
        //Adding elements to map  
        map.put(1,"Amit");  
        map.put(5,"Rahul");  
        map.put(2,"Jai");  
        map.put(6,"Amit");  
        System.out.println(map);
        System.out.println(map.get(1));
        System.out.println(map.containsKey(1));
        System.out.println(map.size());
        System.out.println(map.isEmpty());
    }
    }
    
    
    Output
    {1=Amit, 2=Jai, 5=Rahul, 6=Amit}
    Amit
    true
    4
    false
    
    
  • The following program generates a frequency table of the words found in the String sample . The frequency table maps each word to the number of times it occurs in the argument list.


  •  
    import java.util.*;
    
    public class Freq {
        public static void main(String[] args) {
            Map m = new HashMap();
            String sample[] ={"I", "am", "a", "great", "human", "I", "am", "also", "going", "to", "school"};
            // Initialize frequency table from command line
            for (String a : sample) {
                Integer freq = m.get(a);
                m.put(a, (freq == null) ? 1 : freq + 1);
            }
    
            System.out.println(m.size() + " distinct words:");
            System.out.println(m);
            
            
        }
    }
    
    Output
    9 distinct words:
    {a=1, going=1, school=1, I=2, also=1, to=1, am=2, great=1, human=1}
    
    
  • Suppose you'd prefer to see the frequency table in alphabetical order. All you have to do is change the implementation type of the Map from HashMap to TreeMap. Making this four-character change causes the program to generate the following output from the same command line.


  • Similarly, you could make the program print the frequency table in the order the words first appear on the command line simply by changing the implementation type of the map to LinkedHashMap. Doing so results in the following output.


  •  
    import java.util.*;
    
    public class Freq {
        public static void main(String[] args) {
            Map m = new TreeMap();
             Map m1 = new LinkedHashMap();
            String sample[] ={"I", "am", "a", "great", "human", "I", "am", "also", "going", "to", "school"};
            // Initialize frequency table from command line
            for (String a : sample) {
                Integer freq = m.get(a);
                m.put(a, (freq == null) ? 1 : freq + 1);
                freq = m1.get(a);
                m1.put(a, (freq == null) ? 1 : freq + 1);
            }
    
            System.out.println("Treemap" + m);
            System.out.println("LinkedHashMap" + m1);
            
        }
    }
    
    Output
    Treemap{I=2, a=1, also=1, am=2, going=1, great=1, human=1, school=1, to=1}
    LinkedHashMap{I=2, am=2, a=1, great=1, human=1, also=1, going=1, to=1, school=1}
    
    
     
    import java.util.*;  
    public class MapExample1 {  
    public static void main(String[] args) {  
        Map map=new HashMap();  
        //Adding elements to map  
        map.put(1,"Amit");  
        map.put(5,"Rahul");  
        map.put(2,"Jai");  
        map.put(6,"Amit");  
        //Traversing Map  
        Set set=map.entrySet();//Converting to Set so that we can traverse  
        Iterator itr=set.iterator();  
        while(itr.hasNext()){  
            //Converting to Map.Entry so that we can get key and value separately  
            Map.Entry entry=(Map.Entry)itr.next();  
            System.out.println(entry.getKey()+" "+entry.getValue());  
        }  
    }  
    }
    
    Output
    1 Amit
    2 Jai
    5 Rahul
    6 Amit
    
    
     
    import java.util.*;  
    class MapExample2{  
     public static void main(String args[]){  
      Map map=new HashMap();  
      map.put(100,"Amit");  
      map.put(101,"Vijay");  
      map.put(102,"Rahul");  
      //Elements can traverse in any order  
      for(Map.Entry m:map.entrySet()){  
       System.out.println(m.getKey()+" "+m.getValue());  
      }  
     }  
    }
    
    Output
    102 Rahul
    100 Amit
    101 Vijay
    
    
     
    import java.util.*;  
    class MapExample3{  
     public static void main(String args[]){  
    Map map=new HashMap();          
          map.put(100,"Amit");    
          map.put(101,"Vijay");    
          map.put(102,"Rahul");   
          //Returns a Set view of the mappings contained in this map        
          map.entrySet()  
          //Returns a sequential Stream with this collection as its source  
          .stream()  
          //Sorted according to the provided Comparator  
          .sorted(Map.Entry.comparingByKey())  
          //Performs an action for each element of this stream  
          .forEach(System.out::println);  
     }  
    }  
    Output:
    
    100=Amit
    101=Vijay
    102=Rahul
    
    
     
    import java.util.*;  
    class MapExample4{  
     public static void main(String args[]){  
    Map map=new HashMap();          
          map.put(100,"Amit");    
          map.put(101,"Vijay");    
          map.put(102,"Rahul");    
          //Returns a Set view of the mappings contained in this map    
          map.entrySet()  
          //Returns a sequential Stream with this collection as its source  
          .stream()  
          //Sorted according to the provided Comparator  
          .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))  
          //Performs an action for each element of this stream  
          .forEach(System.out::println);  
     }  
    }  
    Output:
    
    102=Rahul
    101=Vijay
    100=Amit
    
    
     
    import java.util.*;  
    class MapExample5{  
     public static void main(String args[]){  
    Map map=new HashMap();          
          map.put(100,"Amit");    
          map.put(101,"Vijay");    
          map.put(102,"Rahul");    
          //Returns a Set view of the mappings contained in this map    
          map.entrySet()  
          //Returns a sequential Stream with this collection as its source  
          .stream()  
          //Sorted according to the provided Comparator  
          .sorted(Map.Entry.comparingByValue())  
          //Performs an action for each element of this stream  
          .forEach(System.out::println);  
     }  
    }  
    Output:
    
    100=Amit
    102=Rahul
    101=Vijay
    
    
     
    import java.util.*;  
    class MapExample6{  
     public static void main(String args[]){  
    Map map=new HashMap();          
          map.put(100,"Amit");    
          map.put(101,"Vijay");    
          map.put(102,"Rahul");    
         //Returns a Set view of the mappings contained in this map    
         map.entrySet()  
         //Returns a sequential Stream with this collection as its source  
         .stream()  
         //Sorted according to the provided Comparator  
         .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))  
         //Performs an action for each element of this stream  
         .forEach(System.out::println);  
     }  
    }  
    Output:
    
    101=Vijay
    102=Rahul
    100=Amit