HashMap<Key, Value> is a component of the Java Collection Framework and belongs to the java.util package. It stores data in the structure of Key and Value pairs, where the keys must be unique. Although you can sort a Map<Key, Value> based on its values in Java, there isn’t a direct function available to sort it by values.
In this article, we will examine the techniques that can be employed to sort a map by its values.
In Java, a Map represents a collection of values structured as key-value pairs. Nonetheless, the entries in a Map are unordered by default. If you wish to arrange the map by its values (not its keys), an additional step is necessary since the Map itself does not sort by values.
To arrange the values of a map in Java, you can convert the map into a list, sort the list by values, and then reinsert the sorted entries into a map. This method is quite straightforward, and there are numerous other approaches to accomplish the task.
Now, before delving into how to sort a Map by its values, let’s review some methods associated with the Map in Java.
HashMap
Time Complexity
put
O(1)
remove
O(1)
get
O(1)
containsKey
O(1)
The space complexity of HashMap is O(n), where n signifies the number of entries present in the map.
Java Certification Training Course
This is an extensive training module in the Java programming language that will facilitate your advancement in the software development field.
Various Methods to Sort a HashMap by Values in Java
There are numerous ways to arrange a Map<Key, Value> based on its values in Java. Some of them include:
1. Utilizing List<Map.Entry<K, V>> and Comparator in Java
This is the most prevalent and straightforward method to order a map by its values. It necessitates converting the Map values into a list, sorting the list, and then reinserting it back into a map.
Steps to arrange values using a list:
Transform the map values to a list.
Sort the list using a custom comparator that compares the values.
Example:
Java
Code Copied!
var isMobile = window.innerWidth “);
editor34577.setValue(decodedContent); // Set the default text
editor34577.clearSelection();
function closeOutput68593() {
var code = editor68593.getSession().getValue();
jQuery(“.maineditor68593 .code-editor-output”).hide();
}
// Assign event listeners to the buttons
document.getElementById(“copyBtn68593”).addEventListener(“click”, copyCodeToClipboard68593);
document.getElementById(“runBtn68593”).addEventListener(“click”, runCode68593);
document.getElementById(“closeoutputBtn68593”).addEventListener(“click”, closeOutput68593);
Result:
Clarification: In the preceding Java code, the values of the Map are transformed into a List. Subsequently, the List is organized by the values using a custom comparator. Thereafter, the ordered entries are incorporated into the LinkedHashMap. Finally, it gets printed.
2. Employing Stream API in Java
The Stream API was unveiled in Java 8, providing data processing in a functional manner. It encompasses operations like filtering, mapping, and sorting, which can be applied with Collections. While dealing with a Map, we initially convert the collections into a stream of entries to enable us to execute stream operations like sorting on it.
Procedure to Organize the Values using a Stream API:
You can employ the entrySet() method to change the map into a stream of key-value pairs.
Next, organize the values using the sorted() method, and then provide a comparator that compares entries based on their values.
Following that, utilize the collect() method to gather the organized entries into a LinkedHashMap to ensure the order of the values is maintained.
Illustration:
Java
Code Duplicated!
var isMobile = window.innerWidth map = new HashMap();n map.put(“Apple”, 40);n map.put(“Banana”, 20);n map.put(“Cherry”, 50);n map.put(“Date”, 10);nn // Organizing the mapn Map sortedMap = map.entrySet()n .stream()n .sorted(Map.Entry.comparingByValue()) // Sort by valuen .collect(Collectors.toMap(n Map.Entry::getKey, n Map.Entry::getValue, n (e1, e2) -> e1, n LinkedHashMap::new n ));nn System.out.println(“Before organizing: ” + map);n System.out.println(“Organized Map by Values: ” + sortedMap);n }n}nn”);
function closeOutput68593() {
var code = editor68593.getSession().getValue();
jQuery(“.maineditor68593 .code-editor-output”).hide();
}
// Assign event listeners to the buttons
document.getElementById(“copyBtn68593”).addEventListener(“click”, copyCodeToClipboard68593);
document.getElementById(“runBtn68593”).addEventListener(“click”, runCode68593);
document.getElementById(“closeoutputBtn68593”).addEventListener(“click”, closeOutput68593);
“““html
.code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn68593”).addEventListener(“click”, copyCodeToClipboard68593);
document.getElementById(“runBtn68593”).addEventListener(“click”, runCode68593);
document.getElementById(“closeoutputBtn68593”).addEventListener(“click”, closeoutput68593);
Result:
Clarification: In the preceding Java code, the Stream API is utilized to transform the map’s entries into a stream, subsequently organizing them by values. After sorting, it gathers the ordered entries into a LinkedHashMap to preserve the sequence. The outcome is a sorted LinkedHashMap with entries arranged by their values.
3. Utilizing Lambda Expressions in Java
A lambda expression provides a concise method to define a function in Java. They facilitate the creation of anonymous functions, which are brief snippets of code that can be executed.
Steps to arrange values basedon a lambda expression:
Initially, convert the Map entries into a stream via the entrySet() method, which yields a collection of key-value pairs.
Next, organize the stream produced in the previous step using a lambda expression. We will implement the sorted() method alongside a lambda expression that compares the map entries by their values.
Ultimately, we can assemble the sorted entries into a LinkedHashMap.
Illustration:
Java
Code Copied!
var isMobile = window.innerWidth “);
editor67242.setValue(decodedContent); // Set the default text
editor67242.clearSelection();
editor67242.setOptions({
maxLines: Infinity
});
function decodeHTML67242(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard67242() {
const code = editor67242.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
function closeoutput67242() {
var code = editor67242.getSession().getValue();
jQuery(".maineditor67242 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn67242").addEventListener("click", copyCodeToClipboard67242);
document.getElementById("runBtn67242").addEventListener("click", runCode67242);
document.getElementById("closeoutputBtn67242").addEventListener("click", closeoutput67242);
Result:
Clarification: In the preceding Java code, the lambda expression is employed to arrange a Map by its values. Initially, it contrasts the map values through the lambda expression. After that, these entries are gathered into a LinkedHashMap so that the sequence is upheld.
4. Utilizing sort() Method in Java
This approach employs the sort() method to arrange the Map entries by values. As the Map itself does not retain a sequence, the sort() method can be utilized to organize the Map values in Java.
Steps to order the values utilizing a sort() method:
Transform the Map entries into a List: Given that a Map does not support direct sorting, we will first convert the Map entries into a list of Map.Entry<K, V> objects.
Employ the sort() method: Once we have the Map values in
“““html
To arrange a collection, one can employ the sort() function of the List interface or the Collections.sort() function to organize the elements.
Example:
Java
Code Copied!
var isMobile = window.innerWidth “);
editor52355.setValue(decodedContent); // Set the default text
editor52355.clearSelection();
editor52355.setOptions({
maxLines: Infinity
});
function decodeHTML52355(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard52355() {
const code = editor52355.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor52355 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor52355 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Error copying code: “, err);
});
}
function runCode52355() {
var code = editor52355.getSession().getValue();
function closeoutput52355() {
var code = editor52355.getSession().getValue();
jQuery(".maineditor52355 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn52355").addEventListener("click", copyCodeToClipboard52355);
document.getElementById("runBtn52355").addEventListener("click", runCode52355);
document.getElementById("closeoutputBtn52355").addEventListener("click", closeoutput52355);
Output:
Clarification: The preceding code organizes a Map based on its values utilizing the sort() method. Initially, it transforms the map into a list, and subsequently sorts that list in ascending order based on the values.
Note: It is not feasible to perform sorting directly on a map without a prior conversion to a list; hence, the sort() method is implemented. Additionally, Collections.reverseOrder() can be used to arrange the values in reverse order.
5. Utilizing collect() and toMap() Method in Java
This technique employs the Stream API to arrange a Map according to its values and then accumulates the ordered values into another Map. It transforms the Map into a stream and subsequently gathers the results into a new Map using the collect() method alongside Collectors.toMap().
Example:
Java
Code Copied!
var isMobile = window.innerWidth
``````html
");
editor74177.setValue(decodedContent); // Assign the default text
editor74177.clearSelection();
editor74177.setOptions({
maxLines: Infinity
});
function decodeHTML74177(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard74177() {
const code = editor74177.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery(".maineditor74177 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor74177 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode74177() {
var code = editor74177.getSession().getValue();
function closeoutput74177() {
var code = editor74177.getSession().getValue();
jQuery(".maineditor74177 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn74177").addEventListener("click", copyCodeToClipboard74177);
document.getElementById("runBtn74177").addEventListener("click", runCode74177);
document.getElementById("closeoutputBtn74177").addEventListener("click", closeoutput74177);
Output:
Explanation: In the preceding Java code, a Map is arranged according to its values, subsequently accumulating the sorted entries into a new Map. The collect() method is then employed to store the sorted entries into a newly created LinkedHashMap, which preserves the sequence. This approach generates a fresh sorted map without modifying the original.
6. Implementing Custom Code in Java
This approach involves crafting your own logic to arrange a map, rather than relying on the built-in tools such as Stream or Collections.sort(), similar to other procedures. For instance, you can traverse the map values, compare them, and organize them based on your criteria. This technique is advantageous when a specific sorting method is necessary that is not provided by Java’s built-in functions.
Example:
Java
Code Copied!
var isMobile = window.innerWidth ");
editor44539.setValue(decodedContent); // Assign the default text
editor44539.clearSelection();
editor44539.setOptions({
maxLines: Infinity
});
function decodeHTML44539(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard44539() {
const code = editor44539.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
jQuery(".maineditor44539 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor44539 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
``````javascript
copying code: ", err);
});
}
function dismissOutput44539() {
var code = editor44539.getSession().getValue();
jQuery(".maineditor44539 .code-editor-output").hide();
}
// Assign event listeners to the buttons
document.getElementById("copyBtn44539").addEventListener("click", copyCodeToClipboard44539);
document.getElementById("runBtn44539").addEventListener("click", executeCode44539);
document.getElementById("closeoutputBtn44539").addEventListener("click", dismissOutput44539);
Result:
Description: In the Java example above, a Map is utilized to organize its values through a manual method. Initially, the map is transformed into a list of values. Subsequently, a loop is employed to compare and switch them, enabling control over the Map's flow.
Comparison of Various Techniques for Sorting Values in a Map
Techniques
Time Complexity
Code Complexity
Adaptability
Ideal For
List<Map.Entry<K, V>> and Comparator
O(n log n)
Moderate
Highly customizable sorting method
Pre-Java 8 projects or fine control
Stream API
O(n log n)
Low
Medium – concise yet structured
Medium – simple to adjust the comparator
Lambda Expressions
O(n log n)
Low
High – effortlessly incorporates custom logic
Clear and expressive sorting requirements
sort() on List of Entries
O(n log n)
Low to Moderate
sort() on the List of Entries
Rapid implementations and personalized sort orders
collect() + toMap()
O(n log n)
Low
Medium – optimal with LinkedHashMap
One-liners in production or stream processes
Custom Sorting Code (manual implementation)
O(n²) or O(n log n)
High
Very High – complete control over logic
Educational scenarios or highly specialized cases
Complimentary Online Java Certification Course
This free Java certification program can assist you in acquiring the essential skills necessary to present yourself as a competent Java professional and secure lucrative job prospects in leading MNCs.
While you cannot directly sort the values of a Map in Java, various methods enable it. Options include using List, Comparator, Stream API, lambda, or collect() functions, contingent on your Java version and preference. Each approach has distinct advantages and drawbacks. It’s advisable to utilize LinkedHashMap as it preserves the order of sorted values.
To improve your knowledge of Java, you may refer to our Java Course.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.