HashMap and TreeMap in Java
Last Updated :
02 Jun, 2023
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.
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:
- HashMap implements Map interface while TreeMap implements SortedMap interface. A Sorted Map interface is a child of Map.
- 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.
- 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.
Related Articles
Similar Reads
TreeMap headMap() Method in Java
The java.util.TreeMap.headMap(key_point) method of TreeMap class is used to get all the pairs or portion of the map strictly less than the parameter key_value. The mentioned parameter is excluded from the newly prepared treemap. Since the set is backed by the map, so any changes to the map are refle
3 min read
TreeMap in Java
TreeMap is a part of the Java Collection Framework. It implements the Map and NavigableMap interface and extends the AbstractMap class. It stores key-value pairs in a sorted order based on the natural ordering of keys or a custom Comparator. It uses a Red-Black Tree for efficient operations (add, re
11 min read
HashMap in Java
In Java, HashMap is part of the Java Collections Framework and is found in the java.util package. It provides the basic implementation of the Map interface in Java. HashMap stores data in (key, value) pairs. Each key is associated with a value, and you can access the value by using the corresponding
15+ min read
Hashmap vs WeakHashMap in Java
HashMap Java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair. Even though the object is specified as key in hashmap, it does not have any reference and it is not eligible for garbage collection if it is associated with HashMap i.e. HashMap dominates o
3 min read
HashMap clear() Method in Java
The clear() method of the HashMap class in Java is used to remove all of the elements or mappings (key-value pairs) from a specified HashMap.Example 2: Here, we will use the clear() method to clear a HashMap of Integer keys and String values. Java// Clearing HashMap of Integer keys // and String val
2 min read
HashMap clone() Method in Java
The clone() method of the HashMap class in Java is used to create a shallow copy of the specified HashMap. The method returns a new HashMap that contains the same key-value mappings as the original HashMap.Example 1: Here, we will use the clone() method to clone a HashMap of Integer keys and String
2 min read
SortedMap headMap() method in Java
The headMap() method of SortedMap interface in Java is used to return a view of the portion of this map whose keys are strictly less than toKey. The map returned by this method is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The map returned by this m
2 min read
HashMap size() Method in Java
The size() method of the Java HashMap class is used to retrieve the number of key-value pairs currently stored in the HashMap.Example 1: This example demonstrates the use of the size() method to get the number of elements in the HashMap.Java// Java program to demonstrates the working of size() impor
2 min read
HashMap entrySet() Method in Java
The entrySet() method of the HashMap class in Java is used to create a set view of the mappings contained in the HashMap. This method allows us to iterate over the key-value pairs in the map or convert them into a set.Example 1: Here, we will use the entrySet() method to view the mappings in a HashM
2 min read
NavigableMap headMap() in Java
The headMap() method of NavigableMap interface in Java is used to return a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.The returned
2 min read