In this article, we will discuss how to convert unordered HashMap into Sorted TreeMap
We can sort HashMap in both ascending and descending order, by passing HashMap contents as argument to TreeMap’s inter-conversion constructor
1. Solution for HashMap to TreeMap for Keys :
- Ascending order: pass HashMap entries as arguments to TreeMap class’ inter-conversion constructor
- Descending order: Implement Comparator interface by providing reverse sorting logic and finally putting all entries of HashMap into TreeMap classs using putAll() method
1.1 Sorting in Ascending order of Keys :
- Converting Unordered HashMap to Sorted TreeMap in ascending order
- Syntax :
TreeMap<String, String> set = new TreeMap<String, String>(hashMap);
SortingHashMapInAscendingOrder.java
package in.bench.resources.java.map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class SortingHashMapInAscendingOrder {
public static void main(String[] args) {
// 1. create HashMap object of type <String, String>
HashMap<String, String> hm = new HashMap<String, String>();
// 1.1 adding key-value pairs to HashMap object
hm.put("Microsoft", "Bill Gates");
hm.put("Apple Inc", "Steve Jobs");
hm.put("Google", "Sundar Pichai");
hm.put("LinkedIn", "Reid Hoffman");
hm.put("Facebook", "Mark Zuckerberg");
// 1.2 print to console - Random Order iterating
System.out.println("Before Sorting : Random Order \n");
// 1.3 getting keySet() into Set
Set<String> set = hm.keySet();
// 1.4 get Iterator from key set
Iterator<String> itr = set.iterator();
// 1.5 iterating in random order
while(itr.hasNext()) {
String key = itr.next();
System.out.println("Key : " + key + "\t\t"
+ "Value : " + hm.get(key));
}
// 2. After Sorting : Ascending order
System.out.println("\n\n\nAfter Sorting : Ascending order of Keys \n");
// 2.1 convert to TreeMap
Map<String, String> ts = new TreeMap<String, String>(hm);
// 2.2 iterate/print - ascending order of keys
for(String strKey : ts.keySet()){
System.out.println("Key : " + strKey + "\t\t"
+ "Value : " + hm.get(strKey));
}
}
}
Output:
Before Sorting : Random Order
Key : Apple Inc Value : Steve Jobs
Key : Google Value : Sundar Pichai
Key : LinkedIn Value : Reid Hoffman
Key : Microsoft Value : Bill Gates
Key : Facebook Value : Mark Zuckerberg
After Sorting : Ascending order of Keys
Key : Apple Inc Value : Steve Jobs
Key : Facebook Value : Mark Zuckerberg
Key : Google Value : Sundar Pichai
Key : LinkedIn Value : Reid Hoffman
Key : Microsoft Value : Bill Gates
1.2 Sorting in Descending order of Keys :
- Converting Unordered HashMap to Sorted TreeMap in descending order
- Syntax :
TreeMap<String, String> map = new TreeMap<String, String>(reverseCompLogic);
map.putAll(hashMap);
SortingHashMapInDescendingOrder.java
package in.bench.resources.java.map;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class SortingHashMapInDescendingOrder {
public static void main(String[] args) {
// 1. create HashMap object of type <String, String>
HashMap<String, String> hm = new HashMap<String, String>();
// 1.1 adding key-value pairs to HashMap object
hm.put("Microsoft", "Bill Gates");
hm.put("Apple Inc", "Steve Jobs");
hm.put("Google", "Sundar Pichai");
hm.put("LinkedIn", "Reid Hoffman");
hm.put("Facebook", "Mark Zuckerberg");
// 1.2 print to console - Random Order iterating
System.out.println("Before Sorting : Random Order \n");
// 1.3 getting keySet() into Set
Set<String> set = hm.keySet();
// get Iterator from key set
Iterator<String> itr = set.iterator();
// 1.4 iterating in random order
while(itr.hasNext()) {
String key = itr.next();
System.out.println("Key : " + key + "\t\t"
+ "Value : " + hm.get(key));
}
// 2. After Sorting : Ascending order
System.out.println("\n\n\nAfter Sorting : Descending order of Keys \n");
// 2.1 convert to TreeMap
Map<String, String> ts = new TreeMap<String, String>(
Collections.reverseOrder());
// 2.2 put all key-value into TreeMap
ts.putAll(hm);
// 2.3 iterate/print - descending order of keys
for(String strKey : ts.keySet()){
System.out.println("Key : " + strKey + "\t\t"
+ "Value : " + hm.get(strKey));
}
}
}
Output:
Before Sorting : Random Order
Key : Apple Inc Value : Steve Jobs
Key : Google Value : Sundar Pichai
Key : LinkedIn Value : Reid Hoffman
Key : Microsoft Value : Bill Gates
Key : Facebook Value : Mark Zuckerberg
After Sorting : Descending order of Keys
Key : Microsoft Value : Bill Gates
Key : LinkedIn Value : Reid Hoffman
Key : Google Value : Sundar Pichai
Key : Facebook Value : Mark Zuckerberg
Key : Apple Inc Value : Steve Jobs
2. String & Wrapper classes v/s Custom Object :
- Since, we are dealing with String objects, actually we don’t have to do much work here as String class’ already implements Comparable interface, otherwise we have to code for object comparison as explained in below articles
- Object comparison using Comparable – Custom object with Comparable interface
- Object comparison using Comparator – Custom object with Comparator interface
3. Important points to remember about Map :
- HashMap stores entries (Key-Value pairs) in random-order of Keys
- LinkedHashMap stores entries (Key-Value pairs) as per insertion-order of Keys
- TreeMap stores entries (Key-Value pairs) in sorted-order of Keys
Related Articles:
- Java – Sorting HashMap by Keys and Values
- Java – Converting Unordered HashMap into Sorted TreeMap
- Java – How to sort LinkedHashMap by its Keys ?
- Java – How to sort LinkedHashMap by its Values ?
- Java – How to Sort TreeMap by it Keys in descending-order ?
- Java – Sorting Hashtable contents
- Java 8 – Sorting HashMap by Keys and Values using Stream
- Java 8 – How to Sort HashMap entries by its Keys – 6 ways ?
- Java 8 – How to Sort HashMap entries by its Values – 6 ways ?
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
- https://docs.oracle.com/javase/tutorial/collections/implementations/list.html
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
- https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
- https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
Happy Coding !!
Happy Learning !!