HashMap in Java

Java HashMap

Java HashMap class hierarchy

Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc. HashMap class is found in the java.util package.

HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and implements the Map interface.

Points to remember

  • Java HashMap contains values based on the key.
  • Java HashMap contains only unique keys.
  • Java HashMap may have one null key and multiple null values.
  • Java HashMap is non synchronized.
  • Java HashMap maintains no order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Hierarchy of HashMap class

As shown in the above figure, HashMap class extends AbstractMap class and implements Map interface.

HashMap class declaration

  1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable  

HashMap class Parameters

Let's see the Parameters for java.util.HashMap class.

  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.

Constructors of Java HashMap class

ConstructorDescription
HashMap()It is used to construct a default HashMap.
HashMap(Map<? extends K,? extends V> m)It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity)It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor)It is used to initialize both the capacity and load factor of the hash map by using its arguments.

Methods of Java HashMap class

MethodDescription
void clear()It is used to remove all of the mappings from this map.
boolean isEmpty()It is used to return true if this map contains no key-value mappings.
Object clone()It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet()It is used to return a collection view of the mappings contained in this map.
Set keySet()It is used to return a set view of the keys contained in this map.
V put(Object key, Object value)It is used to insert an entry in the map.
void putAll(Map map)It is used to insert the specified map in the map.
V putIfAbsent(K key, V value)It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key)It is used to delete an entry for the specified key.
boolean remove(Object key, Object value)It removes the specified values with the associated specified keys from the map.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value)This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key)This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o)It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action)It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key)This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue)It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty()This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value)It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue)It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection<V> values()It returns a collection view of the values contained in the map.
int size()This method returns the number of entries in the map.



HashMap Example


  1. //store student name and roll no
    package com.test;
     
    import java.util.HashMap;
     
    public class HashMapEx1 {
     
           /*
            * 101 = Rahul
            * 102 = Papu
            * 103 = Prabhat
            * 104 = Sagar
            */
           public static void main(String[] args) {
                 
                  HashMap hmStudent = new HashMap();
                 
                  hmStudent.put("101", "Rahul");
                  hmStudent.put("102", "Papu");
                  hmStudent.put("103", "Prabhat");
                  hmStudent.put("104", "Sagar");
                  hmStudent.put("101", "Rani");
                 
                  System.out.println(hmStudent);
                  for(int i=101;i<=104;i++){
                         String key = Integer.toString(i);
                         System.out.println(hmStudent.get(key));
                         //System.out.println(hmStudent.get(""+i));
                  }
           }
          
    }


{104=Sagar, 103=Prabhat, 102=Papu, 101=Rani}
Rani
Papu
Prabhat
Sagar

In this example, we are storing String as the key and String as the value. The put() method inserts the elements in the map.

To get the key and value elements, we should call the getKey() and getValue() methods. The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.Entry.

No Duplicate Key on HashMap

You cannot store duplicate keys in HashMap. However, if you try to store duplicate key with another value, it will replace the value.

  1. import java.util.HashMap;
    import java.util.Map;

  2. public class HashMapExample2{ 
           public static void main(String args[]){ 
                  HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap   
                  map.put(1,"Deepak");  //Put elements in Map 
                  map.put(2,"Sagar");   
                  map.put(3,"Prabhat");  
                  map.put(1,"Rahul"); //trying duplicate key 
     
                  System.out.println("Iterating Hashmap..."); 
                  for(Map.Entry m : map.entrySet()){   
                         System.out.println(m.getKey()+" "+m.getValue());   
                  } 
           } 
    1. } 


Iterating Hashmap...
1 Rahul
2 Sagar
3 Prabhat

Java HashMap example to add() elements

Here, we see different ways to insert elements.

  1. import java.util.*;  
  2. class HashMap1{  
  3.  public static void main(String args[]){  
  4.    HashMap<Integer,String> hm=new HashMap<Integer,String>();    
  5.     System.out.println("Initial list of elements: "+hm);  
  6.       hm.put(100,"Amit");    
  7.       hm.put(101,"Vijay");    
  8.       hm.put(102,"Rahul");   
  9.        
  10.       System.out.println("After invoking put() method ");  
  11.       for(Map.Entry m:hm.entrySet()){    
  12.        System.out.println(m.getKey()+" "+m.getValue());    
  13.       }  
  14.         
  15.       hm.putIfAbsent(103"Gaurav");  
  16.       System.out.println("After invoking putIfAbsent() method ");  
  17.       for(Map.Entry m:hm.entrySet()){    
  18.            System.out.println(m.getKey()+" "+m.getValue());    
  19.           }  
  20.       HashMap<Integer,String> map=new HashMap<Integer,String>();  
  21.       map.put(104,"Ravi");  
  22.       map.putAll(hm);  
  23.       System.out.println("After invoking putAll() method ");  
  24.       for(Map.Entry m:map.entrySet()){    
  25.            System.out.println(m.getKey()+" "+m.getValue());    
  26.           }  
  27.  }  
  28. }  
Initial list of elements: {}
After invoking put() method 
100 Amit
101 Vijay
102 Rahul
After invoking putIfAbsent() method 
100 Amit
101 Vijay
102 Rahul
103 Gaurav
After invoking putAll() method 
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi

Java HashMap example to remove() elements

Here, we see different ways to remove elements.

  1. import java.util.*;  
  2. public class HashMap2 {  
  3.    public static void main(String args[]) {  
  4.     HashMap<Integer,String> map=new HashMap<Integer,String>();          
  5.       map.put(100,"Amit");    
  6.       map.put(101,"Vijay");    
  7.       map.put(102,"Rahul");  
  8.       map.put(103"Gaurav");  
  9.     System.out.println("Initial list of elements: "+map);  
  10.     //key-based removal  
  11.     map.remove(100);  
  12.     System.out.println("Updated list of elements: "+map);  
  13.     //value-based removal  
  14.     map.remove(101);  
  15.     System.out.println("Updated list of elements: "+map);  
  16.     //key-value pair based removal  
  17.     map.remove(102"Rahul");  
  18.     System.out.println("Updated list of elements: "+map);  
  19.    }      
  20. }  

Output:

Initial list of elements: {100=Amit, 101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {101=Vijay, 102=Rahul, 103=Gaurav}
Updated list of elements: {102=Rahul, 103=Gaurav}
Updated list of elements: {103=Gaurav}

Java HashMap example to replace() elements

Here, we see different ways to replace elements.

  1. import java.util.*;  
  2. class HashMap3{  
  3.  public static void main(String args[]){  
  4.    HashMap<Integer,String> hm=new HashMap<Integer,String>();    
  5.       hm.put(100,"Amit");    
  6.       hm.put(101,"Vijay");    
  7.       hm.put(102,"Rahul");   
  8.       System.out.println("Initial list of elements:");  
  9.      for(Map.Entry m:hm.entrySet())  
  10.      {  
  11.         System.out.println(m.getKey()+" "+m.getValue());   
  12.      }  
  13.      System.out.println("Updated list of elements:");  
  14.      hm.replace(102"Gaurav");  
  15.      for(Map.Entry m:hm.entrySet())  
  16.      {  
  17.         System.out.println(m.getKey()+" "+m.getValue());   
  18.      }  
  19.      System.out.println("Updated list of elements:");  
  20.      hm.replace(101"Vijay""Ravi");  
  21.      for(Map.Entry m:hm.entrySet())  
  22.      {  
  23.         System.out.println(m.getKey()+" "+m.getValue());   
  24.      }   
  25.      System.out.println("Updated list of elements:");  
  26.      hm.replaceAll((k,v) -> "Ajay");  
  27.      for(Map.Entry m:hm.entrySet())  
  28.      {  
  29.         System.out.println(m.getKey()+" "+m.getValue());   
  30.      }  
  31.  }  
  32. }  
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay

Difference between HashSet and HashMap

HashSet contains only values whereas HashMap contains an entry(key and value).

Java HashMap Example: Book

  1. import java.util.*;    
  2. class Book {    
  3. int id;    
  4. String name,author,publisher;    
  5. int quantity;    
  6. public Book(int id, String name, String author, String publisher, int quantity) {    
  7.     this.id = id;    
  8.     this.name = name;    
  9.     this.author = author;    
  10.     this.publisher = publisher;    
  11.     this.quantity = quantity;    
  12. }    
  13. }    
  14. public class MapExample {    
  15. public static void main(String[] args) {    
  16.     //Creating map of Books    
  17.     Map<Integer,Book> map=new HashMap<Integer,Book>();    
  18.     //Creating Books    
  19.     Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);    
  20.     Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);    
  21.     Book b3=new Book(103,"Operating System","Galvin","Wiley",6);    
  22.     //Adding Books to map   
  23.     map.put(1,b1);  
  24.     map.put(2,b2);  
  25.     map.put(3,b3);  
  26.       
  27.     //Traversing map  
  28.     for(Map.Entry<Integer, Book> entry:map.entrySet()){    
  29.         int key=entry.getKey();  
  30.         Book b=entry.getValue();  
  31.         System.out.println(key+" Details:");  
  32.         System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);   
  33.     }    
  34. }    
  35. }    


Output:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications and Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6


Java HashMap class hierarchy

What is HashMap

HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap.



  • equals(): It checks the equality of two objects. It compares the Key, whether they are equal or not. It is a method of the Object class. It can be overridden. If you override the equals() method, then it is mandatory to override the hashCode() method.
  • hashCode(): This is the method of the object class. It returns the memory reference of the object in integer form. The value received from the method is used as the bucket number. The bucket number is the address of the element inside the map. Hash code of null Key is 0.
  • Buckets: Array of the node is called buckets. Each node has a data structure like a LinkedList. More than one node can share the same bucket. It may be different in capacity.


Insert Key, Value pair in HashMap

We use put() method to insert the Key and Value pair in the HashMap. The default size of HashMap is 16 (0 to 15)


Example

In the following example, we want to insert three (Key, Value) pair in the HashMap.

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

2.     map.put("Aman"19);  

3.     map.put("Sunny"29);  

4.     map.put("Ritesh"39);  

Let's see at which index the Key, value pair will be saved into HashMap. When we call the put() method, then it calculates the hash code of the Key "Aman." Suppose the hash code of "Aman" is 2657860. To store the Key in memory, we have to calculate the index.

Calculating Index

Index minimizes the size of the array. The Formula for calculating the index is:

1.     Index = hashcode(Key) & (n-1)  

Where n is the size of the array. Hence the index value for "Aman" is:

1.     Index = 2657860 & (16-1) = 4  

The value 4 is the computed index value where the Key and value will store in HashMap.


Hash Collision

This is the case when the calculated index value is the same for two or more Keys. Let's calculate the hash code for another Key "Sunny." Suppose the hash code for "Sunny" is 63281940. To store the Key in the memory, we have to calculate index by using the index formula.

1.     Index=63281940 & (16-1) = 4  

The value 4 is the computed index value where the Key will be stored in HashMap. In this case, equals() method check that both Keys are equal or not. If Keys are same, replace the value with the current value. Otherwise, connect this node object to the existing node object through the LinkedList. Hence both Keys will be stored at index 4


Similarly, we will store the Key "Ritesh." Suppose hash code for the Key is 2349873. The index value will be 1. Hence this Key will be stored at index 1.

get() method in HashMap

get() method is used to get the value by its Key. It will not fetch the value if you don't know the Key. When get(K Key) method is called, it calculates the hash code of the Key.

Suppose we have to fetch the Key "Aman." The following method will be called.

1.     map.get(new Key("Aman"));  

It generates the hash code as 2657860. Now calculate the index value of 2657860 by using index formula. The index value will be 4, as we have calculated above. get() method search for the index value 4. It compares the first element Key with the given Key. If both keys are equal, then it returns the value else check for the next element in the node if it exists. In our scenario, it is found as the first element of the node and return the value 19.

Let's fetch another Key "Sunny."

The hash code of the Key "Sunny" is 63281940. The calculated index value of 63281940 is 4, as we have calculated for put() method. Go to index 4 of the array and compare the first element's Key with the given Key. It also compares Keys. In our scenario, the given Key is the second element, and the next of the node is null. It compares the second element Key with the specified Key and returns the value 29. It returns null if the next of the node is null.


Java LinkedHashMap class

Java LinkedHashMap class hierarchy

Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface.

Points to remember

  • Java LinkedHashMap contains values based on the key.
  • Java LinkedHashMap contains unique elements.
  • Java LinkedHashMap may have one null key and multiple null values.
  • Java LinkedHashMap is non synchronized.
  • Java LinkedHashMap maintains insertion order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

LinkedHashMap class declaration

Let's see the declaration for java.util.LinkedHashMap class.

  1. public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>  

LinkedHashMap class Parameters

Let's see the Parameters for java.util.LinkedHashMap class.

  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.

Constructors of Java LinkedHashMap class

ConstructorDescription
LinkedHashMap()It is used to construct a default LinkedHashMap.
LinkedHashMap(int capacity)It is used to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float loadFactor)It is used to initialize both the capacity and the load factor.
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder)It is used to initialize both the capacity and the load factor with specified ordering mode.
LinkedHashMap(Map<? extends K,? extends V> m)It is used to initialize the LinkedHashMap with the elements from the given Map class m.

Methods of Java LinkedHashMap class

MethodDescription
V get(Object key)It returns the value to which the specified key is mapped.
void clear()It removes all the key-value pairs from a map.
boolean containsValue(Object value)It returns true if the map maps one or more keys to the specified value.
Set<Map.Entry<K,V>> entrySet()It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer<? super K,? super V> action)It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue)It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key.
Set<K> keySet()It returns a Set view of the keys contained in the map
protected boolean removeEldestEntry(Map.Entry<K,V> eldest)It returns true on removing its eldest entry.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection<V> values()It returns a Collection view of the values contained in this map.

Java LinkedHashMap Example

  1. import java.util.*;  
  2. class LinkedHashMap1{  
  3.  public static void main(String args[]){  
  4.    
  5.   LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();  
  6.   
  7.   hm.put(100,"Amit");  
  8.   hm.put(101,"Vijay");  
  9.   hm.put(102,"Rahul");  
  10.   
  11. for(Map.Entry m:hm.entrySet()){  
  12.    System.out.println(m.getKey()+" "+m.getValue());  
  13.   }  
  14.  }  
  15. }  
Output:100 Amit
       101 Vijay
       102 Rahul

Java LinkedHashMap Example: Key-Value pair

  1. import java.util.*;  
  2. class LinkedHashMap2{  
  3.  public static void main(String args[]){  
  4.    LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();           
  5.       map.put(100,"Amit");    
  6.      map.put(101,"Vijay");    
  7.      map.put(102,"Rahul");    
  8.        //Fetching key  
  9.        System.out.println("Keys: "+map.keySet());  
  10.        //Fetching value  
  11.        System.out.println("Values: "+map.values());  
  12.        //Fetching key-value pair  
  13.        System.out.println("Key-Value pairs: "+map.entrySet());  
  14.  }  
  15. }  
Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]


Java TreeMap class

Java TreeMap class hierarchy

Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order.

The important points about Java TreeMap class are:

  • Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • Java TreeMap contains only unique elements.
  • Java TreeMap cannot have a null key but can have multiple null values.
  • Java TreeMap is non synchronized.
  • Java TreeMap maintains ascending order.

TreeMap class declaration

Let's see the declaration for java.util.TreeMap class.

  1. public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable  

TreeMap class Parameters


  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.

Constructors of Java TreeMap class

ConstructorDescription
TreeMap()It is used to construct an empty tree map that will be sorted using the natural order of its key.
TreeMap(Comparator<? super K> comparator)It is used to construct an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map<? extends K,? extends V> m)It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap<K,? extends V> m)It is used to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Methods of Java TreeMap class

MethodDescription
Map.Entry<K,V> ceilingEntry(K key)It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key)It returns the least key, greater than the specified key or null if there is no such key.
void clear()It removes all the key-value pairs from a map.
Object clone()It returns a shallow copy of TreeMap instance.
Comparator<? super K> comparator()It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet<K> descendingKeySet()It returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap<K,V> descendingMap()It returns the specified key-value pairs in descending order.
Map.Entry firstEntry()It returns the key-value pair having the least key.
Map.Entry<K,V> floorEntry(K key)It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer<? super K,? super V> action)It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
SortedMap<K,V> headMap(K toKey)It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap<K,V> headMap(K toKey, boolean inclusive)It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry<K,V> higherEntry(K key)It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key)It is used to return true if this map contains a mapping for the specified key.
Set keySet()It returns the collection of keys exist in the map.
Map.Entry<K,V> lastEntry()It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry<K,V> lowerEntry(K key)It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
K lowerKey(K key)It returns the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet<K> navigableKeySet()It returns a NavigableSet view of the keys contained in this map.
Map.Entry<K,V> pollFirstEntry()It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry<K,V> pollLastEntry()It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value)It inserts the specified value with the specified key in the map.
void putAll(Map<? extends K,? extends V> map)It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value)It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue)It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)It returns key-value pairs whose keys range from fromKey to toKey.
SortedMap<K,V> subMap(K fromKey, K toKey)It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap<K,V> tailMap(K fromKey)It returns key-value pairs whose keys are greater than or equal to fromKey.
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive)It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey.
boolean containsKey(Object key)It returns true if the map contains a mapping for the specified key.
boolean containsValue(Object value)It returns true if the map maps one or more keys to the specified value.
K firstKey()It is used to return the first (lowest) key currently in this sorted map.
V get(Object key)It is used to return the value to which the map maps the specified key.
K lastKey()It is used to return the last (highest) key currently in the sorted map.
V remove(Object key)It removes the key-value pair of the specified key from the map.
Set<Map.Entry<K,V>> entrySet()It returns a set view of the mappings contained in the map.
int size()It returns the number of key-value pairs exists in the hashtable.
Collection values()It returns a collection view of the values contained in the map.

Java TreeMap Example

  1. import java.util.*;  
  2. class TreeMap1{  
  3.  public static void main(String args[]){  
  4.    TreeMap<Integer,String> map=new TreeMap<Integer,String>();    
  5.       map.put(100,"Amit");    
  6.       map.put(102,"Ravi");    
  7.       map.put(101,"Vijay");    
  8.       map.put(103,"Rahul");    
  9.         
  10.       for(Map.Entry m:map.entrySet()){    
  11.        System.out.println(m.getKey()+" "+m.getValue());    
  12.       }    
  13.  }  
  14. }  
Output:100 Amit
       101 Vijay
       102 Ravi
       103 Rahul

What is difference between HashMap and TreeMap?

HashMapTreeMap
1) HashMap can contain one null key.TreeMap cannot contain any null key.
2) HashMap maintains no order.TreeMap maintains ascending order.




Comments

Popular Topics

What is JSP. How to create one JSP application in Eclipse

Data Types in PL/SQL

How to develop a RESTful webservice in java ?

Features of Java

What is JDBC ?

If you have any query or suggestions, Please feel free to write us

Name

Email *

Message *