Sorting a HashMap according to keys in Java
We are given the details of marks scored by students in form of a HashMap, where the name of the student is the Key and the marks scored is the Value. Our task is to sort the map according to the key values i.e the names of the students in the alphabetical(lexicographical) order.
Examples:
Input : Key = Jayant, Value = 80
Key = Anushka, Value = 80
Key = Amit, Value = 75
Key = Abhishek, Value = 90
Key = Danish, Value = 40
Output : Sorted Map according to Names:
Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80
Using TreeMap (putAll method)
The idea is to put all data of HashMap into a TreeMap. The TreeMap follows Red Black Tree based implementation. The map is sorted according to the natural ordering of its keys. Click here for More.
Java
import java.util.*;
class sortmapKey {
static Map<String, Integer> map = new HashMap<>();
public static void sortbykey()
{
ArrayList<String> sortedKeys
= new ArrayList<String>(map.keySet());
Collections.sort(sortedKeys);
for (String x : sortedKeys)
System.out.println( "Key = " + x
+ ", Value = " + map.get(x));
}
public static void main(String args[])
{
map.put( "Jayant" , 80 );
map.put( "Abhishek" , 90 );
map.put( "Anushka" , 80 );
map.put( "Amit" , 75 );
map.put( "Danish" , 40 );
sortbykey();
}
}
|
Output
Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80
Note: The TreeMap provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.
Using TreeMap (Constructor)
Java
import java.util.*;
class sortmapKey {
static Map<String, Integer> map = new HashMap<>();
public static Map<String, Integer>
sortByKey(Map<String, Integer> hm)
{
List<Map.Entry<String, Integer> > list
= new LinkedList<Map.Entry<String, Integer> >(
hm.entrySet());
Collections.sort(
list,
(i1, i2) -> i1.getKey().compareTo(i2.getKey()));
HashMap<String, Integer> temp
= new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
public static void main(String args[])
{
map.put( "Jayant" , 80 );
map.put( "Abhishek" , 90 );
map.put( "Anushka" , 80 );
map.put( "Amit" , 75 );
map.put( "Danish" , 40 );
Map<String, Integer> hm1 = sortByKey(map);
for (Map.Entry<String, Integer> en :
hm1.entrySet()) {
System.out.println( "Key = " + en.getKey()
+ ", Value = "
+ en.getValue());
}
}
}
|
Output
Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80
Using ArrayList
In this approach, we create a list of keys using ArrayList constructor. Then we sort the list using Collections.sort() method.
Java
import static java.util.stream.Collectors.*;
import java.lang.*;
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
class sortmapKey {
static Map<String, Integer> map = new HashMap<>();
public static void sortbykey()
{
HashMap<String, Integer> temp
= map.entrySet()
.stream()
.sorted((i1, i2)
-> i1.getKey().compareTo(
i2.getKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap:: new ));
for (Map.Entry<String, Integer> entry :
temp.entrySet()) {
System.out.println( "Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
public static void main(String args[])
{
map.put( "Jayant" , 80 );
map.put( "Abhishek" , 90 );
map.put( "Anushka" , 80 );
map.put( "Amit" , 75 );
map.put( "Danish" , 40 );
sortbykey();
}
}
|
Output
Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80
Using Java 8 Lambdas
Here we will change how we did sorting and will use lambda expression for sorting. The logic is the same, and even we also passed the comparator object but only using lambda.
Below is the implementation of the above approach:
Output
Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80
Using Java 8 Streams
Here we will use streams to sort the map. We will use the stream() method to get the stream of entrySet followed by the lambda expression inside the sorted() method to sort the stream and finally, we will convert it into a map using toMap() method. Inside the toMap() method, we use the LinkedHashMap::new method reference to retain the sorted order of the map.
Java
import static java.util.stream.Collectors.*;
import java.lang.*;
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
class sortmapKey {
static Map<String, Integer> map = new HashMap<>();
public static void sortbykey()
{
HashMap<String, Integer> temp
= map.entrySet()
.stream()
.sorted((i1, i2)
-> i1.getKey().compareTo(
i2.getKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap:: new ));
for (Map.Entry<String, Integer> entry :
temp.entrySet()) {
System.out.println( "Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
public static void main(String args[])
{
map.put( "Jayant" , 80 );
map.put( "Abhishek" , 90 );
map.put( "Anushka" , 80 );
map.put( "Amit" , 75 );
map.put( "Danish" , 40 );
sortbykey();
}
}
|
Output
Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80
This article is contributed by DANISH KALEEM and Arnav Kr. Mandal.
Last Updated :
29 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...