Program to Convert HashMap to TreeMap in Java
Last Updated :
01 Oct, 2021
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map interface of Java which stores the data in (Key, Value) pairs. To access a value in HashMap, one must know its key. HashMap is known as HashMap because it uses a technique Hashing for storage of data.
The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs.
Below are methods to convert HashMap to TreeMap in Java in such a way that the resultant TreeMap should contain all mappings of the HashMap, sorted by their natural ordering of keys.
Examples:
Input: HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
Output: TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
Input: HashMap: {1=1, 2=2, 3=3}
Output: TreeMap: {1=1, 2=2, 3=3}
Below are methods to convert HashMap to TreeMap in Java:
1. In Java 8: This method includes converting the HashMap to a Stream and collects elements of a stream in a TreeMap using Stream.collect() method which accepts a collector.
Algorithm:
- Get the HashMap to be converted.
- Get the entries from the hashMap
- Convert the map entries into stream
- Using Collectors, collect the entries and convert it into TreeMap
- Now collect the TreeMap
- Return the formed TreeMap
Program:
Java
// Java Program to convert
// HashMap to TreeMap in Java 8
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to construct a new
// TreeMap from HashMap
public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap)
{
Map<K, V>
treeMap = hashMap
// Get the entries from the hashMap
.entrySet()
// Convert the map into stream
.stream()
// Now collect the returned TreeMap
.collect(
Collectors
// Using Collectors, collect the entries
// and convert it into TreeMap
.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue,
newValue)
-> newValue,
TreeMap::new));
// Return the TreeMap
return treeMap;
}
public static void main(String args[])
{
// Create a HashMap
Map<String, String> hashMap = new HashMap<>();
// Add entries to the HashMap
hashMap.put("1", "Geeks");
hashMap.put("2", "forGeeks");
hashMap.put("3", "A computer Portal");
// Print the HashMap
System.out.println("HashMap: " + hashMap);
// construct a new TreeMap from HashMap
Map<String, String> treeMap = convertToTreeMap(hashMap);
// Print the TreeMap
System.out.println("TreeMap: " + treeMap);
}
}
Output:
HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
2. Using Plain Java: In this method, either pass HashMap instance to the TreeMap constructor or to putAll() method. This will directly create the TreeMap from the HashMap.
Algorithm:
- Get the HashMap to be converted.
- Create a new TreeMap
- Pass the hashMap to putAll() method of treeMap
- Return the formed TreeMap
Program:
Java
// Java Program to convert
// HashMap to TreeMap in Java 8
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to construct a
// new TreeMap from HashMap
public static <K, V> Map<K, V> convertToTreeMap(Map<K, V> hashMap)
{
// Create a new TreeMap
Map<K, V> treeMap = new TreeMap<>();
// Pass the hashMap to putAll() method
treeMap.putAll(hashMap);
// Return the TreeMap
return treeMap;
}
public static void main(String args[])
{
// Create a HashMap
Map<String, String> hashMap = new HashMap<>();
// Add entries to the HashMap
hashMap.put("1", "Geeks");
hashMap.put("2", "forGeeks");
hashMap.put("3", "A computer Portal");
// Print the HashMap
System.out.println("HashMap: " + hashMap);
// construct a new TreeMap from HashMap
Map<String, String> treeMap = convertToTreeMap(hashMap);
// Print the TreeMap
System.out.println("TreeMap: " + treeMap);
}
}
Output:
HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
3. Using Google’s Guava library: Guava also provides a TreeMap implementation which can be used to create an empty TreeMap instance.
Algorithm:
- Get the HashMap to be converted.
- Create a new TreeMap using Maps.newTreeMap() of Guava library
- Pass the hashMap to putAll() method of treeMap
- Return the formed TreeMap
Program:
Java
// Java Program to convert
// HashMap to TreeMap in Java 8
import com.google.common.collect.*;
import java.util.*;
import java.util.stream.*;
class GFG {
// Generic function to construct a
// new TreeMap from HashMap
public static <K extends Comparable, V> Map<K, V>
convertToTreeMap(Map<K, V> hashMap)
{
// Create a new TreeMap
Map<K, V> treeMap = Maps.newTreeMap();
// Pass the hashMap to putAll() method
treeMap.putAll(hashMap);
// Return the TreeMap
return treeMap;
}
public static void main(String args[])
{
// Create a HashMap
Map<String, String> hashMap = new HashMap<>();
// Add entries to the HashMap
hashMap.put("1", "Geeks");
hashMap.put("2", "forGeeks");
hashMap.put("3", "A computer Portal");
// Print the HashMap
System.out.println("HashMap: " + hashMap);
// construct a new TreeMap from HashMap
Map<String, String> treeMap = convertToTreeMap(hashMap);
// Print the TreeMap
System.out.println("TreeMap: " + treeMap);
}
}
Output:
HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
4. Conversion between incompatible types: This method can be used if the required TreeMap is of the different type than the HashMap. In this, the conversion needs to be done manually.
Algorithm:
- Get the HashMap to be converted.
- Create a new TreeMap
- For each entry of the hashMap:
- Convert the Key and the Value into the desired type by casting
- Insert the converted pair by put() method of treeMap
- Return the formed TreeMap
Program:
Java
// Java Program to convert
// HashMap to TreeMap in Java 8
import java.util.*;
import java.util.stream.*;
class GFG {
// Function to construct a new TreeMap from HashMap
public static Map<Integer, String>
convertToTreeMap(Map<String, String> hashMap)
{
// Create a new TreeMap
Map<Integer, String> treeMap = new TreeMap<>();
// Convert the HashMap to TreeMap manually
for (Map.Entry<String, String> e : hashMap.entrySet()) {
treeMap.put(Integer.parseInt(e.getKey()), e.getValue());
}
// Return the TreeMap
return treeMap;
}
public static void main(String args[])
{
// Create a HashMap
Map<String, String> hashMap = new HashMap<>();
// Add entries to the HashMap
hashMap.put("1", "Geeks");
hashMap.put("2", "forGeeks");
hashMap.put("3", "A computer Portal");
// Print the HashMap
System.out.println("HashMap: " + hashMap);
// construct a new TreeMap<Integer, String>
// from HashMap<String, String>
Map<Integer, String> treeMap = convertToTreeMap(hashMap);
// Print the TreeMap
System.out.println("TreeMap: " + treeMap);
}
}
Output:
HashMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
TreeMap: {1=Geeks, 2=forGeeks, 3=A computer Portal}
Similar Reads
Java Program to Convert List to HashSet
The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. The HashSet class permits the null element. The class al
4 min read
Java Program to Check if the TreeMap is Empty
The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Approaches: Using the isEmpty() methodU
3 min read
Java Program to Implement TreeMap API
The TreeMap is used to implement Map interface and NavigableMap along with the AbstractMap class in java. The map is sorted by the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Now, in implementing TreeMap API, the task is div
6 min read
How to Convert TreeMap to an ArrayList in Java?
TreeMap is a part of the Java Collection framework. Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. It provides an efficient means of storing key-value pairs in sorted order. Java TreeMap contains only unique elements. It cannot
4 min read
Convert HashMap to LinkedList in Java
HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. LinkedList is a part of the Collection framework present in java.util package. This class is an implementa
2 min read
Program to convert a Map to a Stream in Java
A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are various method to convert Map to Stream in Java: Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which return
4 min read
Java Program to Implement ConcurrentHashMap API
ConcurrentHashMap class obeys the same functional specification as HashTable and includes all the versions of methods corresponding to each method of a HashTable. A HashTable supports the full concurrency of retrievals and adjustable concurrency for updates. All the operations of ConcurrentHashMap a
6 min read
How to Convert a HashSet to JSON in Java?
In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Jav
2 min read
Traverse Through a HashMap in Java
HashMap stores the data in (Key, Value) pairs, and you can access them by an index of another type. HashMap class implements Map interface which allows us to store key. hashMap is a part of the java collections framework been up since Java 1.2. It internally uses hashing technique which is pretty fa
4 min read
Java Program to Get Sorted Sub-Map from TreeMap
TreeMap in Java are containers that store elements in a mapped fashion that is key-value and mapped value pair. Every element has a key-value and a respective mapped value. All the key values are unique and it is necessary that no two mapped values can have the same key value. It is based on Red-Bla
4 min read