Thursday, 3 April 2014

Java Collections , Map Interface

Map is the most important Data Structure in Java. It is used to store Key & Value pairs.
There are commonly 4 implementations of Maps :

  1. HashMap ( No Ordering on Keys or Values )
  2. TreeMap ( Ordered on the basis of Key )
  3. HashTable ( Implemented same as HashMap, except that HashTable is Synchronised . )
  4. LinkedHashMap ( It preserves the order of insertion of elements. )
  1. HashMap

    HashMap is used to store Key and Value pairs in the collection. Here is a very simple example.    


    import java.util.HashMap;
    import java.util.Map.Entry;
    
    public class SimpleHashMapTest {
        public SimpleHashMapTest() {
            super();
        }
    
        public static void main(String[] args) {
            //Create a hash map
            HashMap<Integer, String> map = new HashMap<Integer, String>();
            //add key value pairs in the hashMap
            map.put(1, "First");
            map.put(2, "Second");
            map.put(4, "Fourth");
            map.put(3, "Third");
            map.put(5, "Fifth");
            map.put(6, "Sixth");
            map.put(7, "Seventh");
            
            System.out.println("The key value pairs in HashMap are :");
            for(Entry<Integer,String> e : map.entrySet()){
                System.out.println("Key : "+e.getKey()+"        Val : "+e.getValue());
            }
            //get(key) is used to get the value at the given key
            System.out.println("Value at key : "+3+" is :"+map.get(3));
            //These methods can be used to check if the map contains the particular key or not. 
            //They return boolean
            map.containsKey(1);
            map.containsValue("Sixth");
        }
    }
    

       And the output on the console is as below.



  2. TreeMap

    TreeMap is sortedd on the basis of Key. i.e. if you want to make a key-value pair that need to be sorted on the basis of the key, then you gotta use TreeMap. Let us take an example and try to understand.
    I am taking a self-defined class Animal.class as key and will make a TreeMap. So to make a self-made class a key we need to define implement following interface.
    • Comparable ( This helps in Sorting the keys by comparing them. )
       

    public class Animal implements Comparable{
        String name;
        Integer size;
        public Animal(String name, Integer size) {
            this.name = name;
            this.size = size;
        }
    
        @Override
        public int compareTo(Object o) {
            return ((Animal)o).size - this.size;
        }
        
        public String toString(){
            return size+". "+name;
        }
    }
    
    public class TreeMapTest {
      
        public static void main(String[] args) {
            TreeMap<Animal,Integer> map = new TreeMap<Animal,Integer>();
            map.put(new Animal("Elefant", 10), 1);
            map.put(new Animal("Cat", 3), 2);
            map.put(new Animal("Tiger", 7), 1);
            map.put(new Animal("Lion", 8), 1);
            map.put(new Animal("Deer", 5), 1);
            
            //map.entrySet() gets you a sorted list of key - value pairs
            System.out.println("Sorted list :");
            for(Entry<Animal,Integer> e : map.entrySet()){
                System.out.println("Key is : "+e.getKey()+ " value : "+e.getValue());
            }
            
            // If you want a sorted in descending order you can use map.descendingMap()
            System.out.println("Descending order list :");
            for(Entry<Animal,Integer> e : map.descendingMap().entrySet()){
                System.out.println("Key is : "+e.getKey()+ " value : "+e.getValue());
            }
            
        }
    }
    

    output is  :
  3. HashTable

    HashTable and HashMap are almost same. The little difference between them is that
    • HashTable is synchronised
    • HashMap is unsynchronised
    That means HashTable is Thread safe and HashMap is not. That simply means that if so many threads are modifying a HashTable then locking is handeled by HashTable itself whereas in case of HashMap synchronisation needs to be done.
  4. LinkedHashMap

    LinkedHashMap is similar to HashMap except for the fact that LinkedHashMap maintains the insertion order of the elements in the LinkedHashMap.
    Let us take an example and try to understand.      
    public class Animal implements Comparable{
        String name;
        Integer size;
        public Animal(String name, Integer size) {
            this.name = name;
            this.size = size;
        }
    
        @Override
        public int compareTo(Object o) {
            return ((Animal)o).size - this.size;
        }
        
        public String toString(){
            return size+". "+name;
        }
    }
    
    import java.util.LinkedHashMap;
    import java.util.Map.Entry;
    import java.util.TreeMap;
    
    public class LinkedHashMapTest {
        public static void main(String[] args) {
            LinkedHashMap<Animal,Integer> map = new LinkedHashMap<Animal,Integer>();
            map.put(new Animal("Elefant", 10), 1);
            map.put(new Animal("Cat", 3), 2);
            map.put(new Animal("Tiger", 7), 1);
            map.put(new Animal("Lion", 8), 1);
            map.put(new Animal("Deer", 5), 1);
            
            //map.entrySet() gets you a list of key - value pairs
            System.out.println("List :");
            for(Entry<Animal,Integer> e : map.entrySet()){
                System.out.println("Key is : "+e.getKey()+ " value : "+e.getValue());
            }
            
           
        }
    }
    

  5. OutPut is : 

    Here you can eaisly see that the values are stored in the LinkedHashMap in the order they are inserted.                   

No comments:

Post a Comment