DEV Community

aryan
aryan

Posted on • Updated on • Originally published at java8net.blogspot.com

Sort HashMap By key and By value

In this article, we are going to have look at how to sort HashMap by key and to sort HashMap by value in Java. We are going to learn different approaches to sort HashMap.

Visit this link to read the full article: https://www.java8net.com/2020/02/sort-hashmap-by-key-and-by-value.html

HashMap does not sort its key-value pair and also it does not maintain any order (neither insertion nor sorted). If we want to sort HashMap then we need to provide custom logic that can sort HashMap and sort HashMap by key we can use either TreeMap or LinkedHashMap but in case of sort HashMap by value, we have the only option of LinkedHashMap as TreeMap cannot be used to sort HashMap by value.
To sort HashMap by key, we can use TreeMap class. TreeMap in java is used to store key-value pairs and sort all the pairs w.r.t. keys. We can create a TreeMap from the HashMap and TreeMap sort HashMap by key.

Steps to sort HashMap by key using TreeMap

  1. Create a Comparator, which provides logic to sort HashMap by key.
  2. Create a TreeMap using Comparator.
  3. Add all the entries of HashMap into the TreeMap

Java Sort HashMap Example
HashMap hashMap = new HashMap<>();
hashMap.put("Programming In Java", 450);
hashMap.put("Introduction to Algorithms", 800);
hashMap.put("Data Structures", 600);
hashMap.put("Learn C++", 350);
System.out.println("-----------Before Sorting--------------");
Set> unsortedEntrySet = hashMap.entrySet();
for (Entry entry : unsortedEntrySet) {

System.out.println(entry.getKey() + " = " + entry.getValue());
}

Comparator keyComparator = (s1, s2) -> s1.compareTo(s2);
TreeMap treeMap = new TreeMap<>(keyComparator); treeMap.putAll(hashMap);
System.out.println("-----------After Sorting---------------");
Set> sortedEntrySet = treeMap.entrySet();
for (Entry entry : sortedEntrySet) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}

Visit this link to read the full article: https://www.java8net.com/2020/02/sort-hashmap-by-key-and-by-value.html

Further Learning:
https://www.java8net.com/2020/02/how-to-sort-arraylist-in-java.html
https://www.java8net.com/2020/02/treemap-in-java.html
https://www.java8net.com/2020/03/java-optional.html
https://www.java8net.com/2020/01/lambda-expression-java.html
https://www.java8net.com/2020/01/functional-interface-in-java.html

Top comments (0)