Sorting a HashMap according to keys in Java
Last Updated :
14 Apr, 2025
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.
Java
// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
// This map stores unsorted values
static Map<String, Integer> map = new HashMap<>();
// Function to sort map by Key
public static void sortbykey()
{
// TreeMap to store values of HashMap
TreeMap<String, Integer> sorted = new TreeMap<>();
// Copy all data from hashMap into TreeMap
sorted.putAll(map);
// Display the TreeMap which is naturally sorted
for (Map.Entry<String, Integer> entry : sorted.entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
// Driver Code
public static void main(String args[])
{
// putting values in the Map
map.put("Jayant", 80);
map.put("Abhishek", 90);
map.put("Anushka", 80);
map.put("Amit", 75);
map.put("Danish", 40);
// Calling the function to sortbyKey
sortbykey();
}
}
OutputKey = 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
// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
// This map stores unsorted values
static Map<String, Integer> map = new HashMap<>();
// Function to sort map by Key
public static void sortbykey()
{
// TreeMap to store values of HashMap
TreeMap<String, Integer> sorted
= new TreeMap<>(map);
// Display the TreeMap which is naturally sorted
for (Map.Entry<String, Integer> entry :
sorted.entrySet())
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
// Driver Code
public static void main(String args[])
{
// putting values in the Map
map.put("Jayant", 80);
map.put("Abhishek", 90);
map.put("Anushka", 80);
map.put("Amit", 75);
map.put("Danish", 40);
// Calling the function to sortbyKey
sortbykey();
}
}
OutputKey = 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
// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
// This map stores unsorted values
static Map<String, Integer> map = new HashMap<>();
// Function to sort map by Key
public static void sortbykey()
{
ArrayList<String> sortedKeys
= new ArrayList<String>(map.keySet());
Collections.sort(sortedKeys);
// Display the TreeMap which is naturally sorted
for (String x : sortedKeys)
System.out.println("Key = " + x
+ ", Value = " + map.get(x));
}
// Driver Code
public static void main(String args[])
{
// putting values in the Map
map.put("Jayant", 80);
map.put("Abhishek", 90);
map.put("Anushka", 80);
map.put("Amit", 75);
map.put("Danish", 40);
// Calling the function to sortbyKey
sortbykey();
}
}
OutputKey = 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:
Java
// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
// This map stores unsorted key
static Map<String, Integer> map = new HashMap<>();
// function to sort hashmap by keys
public static Map<String, Integer>
sortByKey(Map<String, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<String, Integer> > list
= new LinkedList<Map.Entry<String, Integer> >(
hm.entrySet());
// Sort the list using lambda expression
Collections.sort(
list,
(i1, i2) -> i1.getKey().compareTo(i2.getKey()));
// put data from sorted list to hashmap
HashMap<String, Integer> temp
= new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
// Driver Code
public static void main(String args[])
{
// putting values in the Map
map.put("Jayant", 80);
map.put("Abhishek", 90);
map.put("Anushka", 80);
map.put("Amit", 75);
map.put("Danish", 40);
// Calling the function to sortbyKey
Map<String, Integer> hm1 = sortByKey(map);
// print the sorted hashmap
for (Map.Entry<String, Integer> en :
hm1.entrySet()) {
System.out.println("Key = " + en.getKey()
+ ", Value = "
+ en.getValue());
}
}
}
OutputKey = 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
// Java Code to sort Map by key value
import static java.util.stream.Collectors.*;
import java.lang.*;
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
class sortmapKey {
// This map stores unsorted values
static Map<String, Integer> map = new HashMap<>();
// Function to sort map by Key
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));
// Display the HashMap which is naturally sorted
for (Map.Entry<String, Integer> entry :
temp.entrySet()) {
System.out.println("Key = " + entry.getKey()
+ ", Value = "
+ entry.getValue());
}
}
// Driver Code
public static void main(String args[])
{
// putting values in the Map
map.put("Jayant", 80);
map.put("Abhishek", 90);
map.put("Anushka", 80);
map.put("Amit", 75);
map.put("Danish", 40);
// Calling the function to sortbyKey
sortbykey();
}
}
OutputKey = 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.
Similar Reads
Sorting a Hashmap according to values
Given the marks scored out of 100 by a student in subjects where the name of the subject is key and marks scored is the value. A HashMap is created using the subject name and respective marks as key-value pairs. The task is to sort the HashMap according to values i.e. according to marks.Example: Inp
9 min read
IdentityHashMap keySet() Method in Java
The java.util.IdentityHashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Syntax: Identity_Hash_Map.keySet() Parameters: The method does n
2 min read
Why String is popular HashMap key in Java?
There are many instances when data is stored as key-value pairs. In Java, it can be achieved by "map" which is a collection. Keys usually should not be null and they should point to only one value. In Map, there are various classes available and among them, Hashmap is a class that implements the Map
3 min read
How to check if a key exists in a HashMap in Java
Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: true Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10 Output: false Using Iterator (Not Efficient): Get the HashMap a
4 min read
How to sort an Array of Strings in Java
Array Of StringsTo sort an array of strings in Java, we can use Arrays.sort() function. Java // A sample Java program to // sort an array of strings // in ascending and descending // orders using Arrays.sort(). import java.util.Arrays; import java.util.Collections; // Driver Class public class SortE
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
Java HashMap keySet() Method
The keySet() method of the Java HashMap class is used to return a set containing all the keys in the map. This set is backed by the HashMap, so if we make any changes to the HashMap, it will be reflected in the Set as well.Example 1: The below Java program demonstrates creating a HashMap, adding key
2 min read
Methods to Create Preallocated HashMap in Java 19
Java 19 has introduced some new methods to create preallocated HashMaps which can enhance the performance of your application. In this article, we will explore the concept of preallocated HashMaps and how to create them using the new methods in Java 19. HashMap is a widely used data structure in Jav
3 min read
ConcurrentHashMap put() method in Java
The put() method in ConcurrentHashMap class in Java is used to associate a given value with a given key in the map. It has the following signature: V put(K key, V value) where: K is the type of key in the map.V is the type of value in the map.Key is the key to be associated with the given value.valu
5 min read
IdentityHashMap hashCode() Method in Java
The java.util.IdentityHashMap.hashCode() method in Java is used to fetch the hash code value of a particular this IdentityHashMap. A map consists of a number of buckets to store the key-value pair. Each bucket has a unique identity and when a key-value pair is inserted into a bucket, the key's hashc
2 min read