The Wayback Machine - https://web.archive.org/web/20240726021959/https://www.geeksforgeeks.org/hashmap-treemap-java/
Open In App

HashMap and TreeMap in Java

Last Updated : 02 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

HashMap and TreeMap are part of collection framework. HashMapjava.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair<Key, Value>.

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

Let us consider below example where we have to count occurrences of each integer in given array of integers.

Input: arr[] = {10, 3, 5, 10, 3, 5, 10};
Output: Frequency of 10 is 3
        Frequency of 3 is 2
        Frequency of 5 is 2

Example:

Java




/* Java program to print frequencies of all elements using
   HashMap */
import java.util.*;
 
class Main
{
    // This function prints frequencies of all elements
    static void printFreq(int arr[])
    {
        // Creates an empty HashMap
        HashMap<Integer, Integer> hmap =
                     new HashMap<Integer, Integer>();
 
        // Traverse through the given array
        for (int i = 0; i < arr.length; i++)
        {
            Integer c = hmap.get(arr[i]);
 
            // If this is first occurrence of element
            if (hmap.get(arr[i]) == null)
               hmap.put(arr[i], 1);
 
            // If elements already exists in hash map
            else
              hmap.put(arr[i], ++c);
        }
 
        // Print result
        for (Map.Entry m:hmap.entrySet())
          System.out.println("Frequency of " + m.getKey() +
                             " is " + m.getValue());
    }
 
    // Driver method to test above method
    public static void main (String[] args)
    {
        int arr[] = {10, 34, 5, 10, 3, 5, 10};
        printFreq(arr);
    }
}


Output:

Frequency of 34 is 1
Frequency of 3 is 1
Frequency of 5 is 2
Frequency of 10 is 3

Key Points

  • HashMap does not maintain any order neither based on key nor on basis of value, If we want the keys to be maintained in a sorted order, we need to use TreeMap.
  • Complexity: get/put/containsKey() operations are O(1) in average case but we can’t guarantee that since it all depends on how much time does it take to compute the hash.

Application: HashMap is basically an implementation of hashing. So wherever we need hashing with key value pairs, we can use HashMap. For example, in Web Applications username is stored as a key and user data is stored as a value in the HashMap, for faster retrieval of user data corresponding to a username.  

TreeMapTreeMap can be a bit handy when we only need to store unique elements in a sorted order. Java.util.TreeMap uses a red-black tree in the background which makes sure that there are no duplicates; additionally it also maintains the elements in a sorted order.

 TreeMap<K, V> hmap = new TreeMap<K, V>();

Below is TreeMap based implementation of same problem. This solution has more time complexity O(nLogn) compared to previous one which has O(n). The advantage of this method is, we get elements in sorted order.

Recommended Practice

Java




/* Java program to print frequencies of all elements using
   TreeMap */
import java.util.*;
 
class Main
{
    // This function prints frequencies of all elements
    static void printFreq(int arr[])
    {
        // Creates an empty TreeMap
        TreeMap<Integer, Integer> tmap =
                     new TreeMap<Integer, Integer>();
 
        // Traverse through the given array
        for (int i = 0; i < arr.length; i++)
        {
            Integer c = tmap.get(arr[i]);
 
            // If this is first occurrence of element  
            if (tmap.get(arr[i]) == null)
               tmap.put(arr[i], 1);
 
            // If elements already exists in hash map
            else
              tmap.put(arr[i], ++c);
        }
 
        // Print result
        for (Map.Entry m:tmap.entrySet())
          System.out.println("Frequency of " + m.getKey() +
                             " is " + m.getValue());
    }
 
    // Driver method to test above method
    public static void main (String[] args)
    {
        int arr[] = {10, 34, 5, 10, 3, 5, 10};
        printFreq(arr);
    }
}


Output:

Frequency of 3 is 1
Frequency of 5 is 2
Frequency of 10 is 3
Frequency of 34 is 1

Key Points

  • For operations like add, remove, containsKey, time complexity is O(log n where n is number of elements present in TreeMap.
  • TreeMap always keeps the elements in a sorted(increasing) order, while the elements in a HashMap have no order. TreeMap also provides some cool methods for first, last, floor and ceiling of keys.

Difference between HashMap and TreeMap:

  HashMap TreeMap
1. It does not provide any order for elements. It provides orders for elements.
2. It’s speed is fast. It’s speed is slow.
3. It allows one key as null and also allows multiple values. It does not allow key as null but it allows multiple null values.
4. It consumes more memory space. It consumes less memory space.
5. It has only basic features. It has advanced features.
6. For comparing keys, equals() is used. For comparing keys, compare or compareTo() is used.
7. It’s complexity is O(1). It’s complexity is O(log n).

Overview:

  1. HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted Map interface is a child of Map.
  2. HashMap implements Hashing, while TreeMap implements Red-Black Tree(a Self Balancing Binary Search Tree). Therefore all differences between Hashing and Balanced Binary Search Tree apply here.
  3. Both HashMap and TreeMap have their counterparts HashSet and TreeSet. HashSet and TreeSet implement Set interface. In HashSet and TreeSet, we have only key, no value, these are mainly used to see presence/absence in a set. For the above problem, we can’t use HashSet (or TreeSet) as we can’t store counts. An example problem where we would prefer HashSet (or TreeSet) over HashMap (or TreeMap) is to print all distinct elements in an array.

collection_interfaces 

Related Articles



Similar Reads

Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java TreeMap, HashMap and LinkedHashMap: What's Similar? All offer a key-&gt;value map and a way to iterate through the keys. The most important distinction between these classes is the time guarantees and the ordering of the keys.All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map int
5 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
There are two variants of descending() in Java.util.TreeMap, both are discussed in this article. 1. descendingKeySet(): It returns a reverse order Navigable Set view of the keys contained in the map. Syntax : public NavigableSet descendingKeySet() Parameters: NA Return Value: It returns a reverse order navigable set view of the keys in this map. Ex
3 min read
Java.util.TreeMap.containskey() and containsValue() in Java
There are two variants of contains() in Java.util.TreeMap, both are discussed in this article. 1. containskey(Object o) : It returns true if the map contains a mapping for the specified key. Parameters: o : The key which will be tested whether present or not. Return Value: Returns true if there is a mapping for the given key. Exception: ClassCastEx
2 min read
Java.util.TreeMap.put() and putAll() in Java
The insertion in TreeMap are handled using the variants of the put functions. There are two variants of put() in Java.util.TreeMap, both are discussed in this article. 1. put() : It associates the specified value with the specified key in the map. If a key is already present, then updating it results in updation of that key. Parameters: key : The k
4 min read
Similarities Between TreeMap and TreeSet in Java
TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed and objects are stored in sorted and ascending order. TreeMap is an implementation of Map Interface . TreeMap is also Implementation of NavigableMap along with AbstractMap class. Similarities between TreeSet and TreeMap in java. Both TreeMap and TreeSet belong
1 min read
Difference between TreeMap and TreeSet in Java
TreeSet is mainly an implementation of SortedSet in java where duplication is not allowed and objects are stored in sorted and ascending order. Some important features of the TreeSet are: In TreeSet duplicate values are not allowed because it implements the SortedSet interface.Objects in a TreeSet are stored in ascending order.In TreeSet the insert
2 min read
TreeMap ceilingEntry() and ceilingKey() methods in Java
There are two variants of ceilingEntry() in Java.util.TreeMap, both are discussed in this article. 1. ceilingEntry(K Key) : It is used to return a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key. Syntax : public Map.Entry ceilingEntry(K key) Parameters : key : The key to be mat
3 min read
TreeMap firstEntry() and firstKey() Method in Java with Examples
There are two variants of first() in Java.util.TreeMap, both are discussed in this article. Method 1: firstEntry() It returns a key-value mapping associated with the least key in this map, or null if the map is empty. Syntax: public Map.Entry firstEntry() Return Type: An entry with the least key and null if the map is empty. Example: Java Code // J
3 min read
three90RightbarBannerImg