How to sort a Map by value in Java
This tutorial explains how to Map<key, value>
sort pairs by value in Java and lists some sample codes to understand it.
There are several ways to Map
sort . Here we use sort()
the , sorted()
method, and Comparator
interface. Let's look at an example.
Use the method to sort sort()
a
in JavaMap
We can sort the elements of a Map using the method List
of the interface . The method sorts the elements in ascending order, and we specify sorting by value using the method. See the following example.sort()
sort()
comparingByValue()
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
List<Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Entry.comparingByValue());
list.forEach(System.out::println);
}
}
Output:
1=100
2=1020
3=300
5=500
After Sorting
1=100
3=300
5=500
2=1020
sorted()
Use the method to Map
sort
in Java
If you are using streams, you can use sorted()
the method to sort the elements in ascending order. We Map.Entry.comparingByValue()
pass as a parameter to the method to sort sorted()
by the value of .Map<key, value>
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
Stream<Map.Entry<Integer, Integer>> sorted =
map.entrySet().stream().sorted(Map.Entry.comparingByValue());
sorted.forEach(System.out::println);
}
}
Output:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
Use the method Comparator
of
in Java to sortsort()
Map<key, value>
In this example, we use compareTo()
the method to compare the value of as parameter sort()
inside the method Map<key, value>
. You can see that we create an Comparator
anonymous inner class of the interface and define compare()
the method to compare the values.
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
List<Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Object>() {
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return ((Comparable<Integer>) ((Map.Entry<Integer, Integer>) (o1)).getValue())
.compareTo(((Map.Entry<Integer, Integer>) (o2)).getValue());
}
});
Map<Integer, Integer> result = new LinkedHashMap<>();
for (Iterator<Entry<Integer, Integer>> it = list.iterator(); it.hasNext();) {
Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) it.next();
result.put(entry.getKey(), entry.getValue());
}
result.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
Output:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
Sort a using the sorted()
and methods
in JavatoMap()
Map
In this example, we sort the using sorted()
the method Map<key, value>
and toMap()
collect the results into the using the method LinkedHashMap
. Here, we use the concept of method reference to create a LinkedHashMap
object.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
Map<Integer, Integer> result = map.entrySet()
.stream()
.sorted(Entry.comparingByValue())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
result.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
Output:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
Map
Sorting
a in Java using custom code
Here, we have created a Comparator
user-defined class that implements the interface and passed its object TreeMap
to to get the sorted sorted by value Map<key, value>
.
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
class UserComparator implements Comparator<Object> {
Map<Integer, Integer> map;
public UserComparator(Map<Integer, Integer> map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
if (map.get(o2) == map.get(o1))
return 1;
else
return ((Integer) map.get(o1)).compareTo((Integer) map.get(o2));
}
}
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
UserComparator comparator = new UserComparator(map);
Map<Integer, Integer> result = new TreeMap<Integer, Integer>(comparator);
result.putAll(map);
result.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
Output:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to Print a HashMap in Java
Publish Date:2025/04/14 Views:84 Category:Java
-
This tutorial explains how to print HashMap an element in Java and also provides some sample code to understand the topic. HashMap It is Map an implementation class of the interface and is used to collect elements into key and value pairs.
Updating Hashmap Values in Java
Publish Date:2025/04/14 Views:88 Category:Java
-
This article explains how to use the two methods contained in the HashMap class in Java - update put() and replace() update the values in a HashMap. hashmap.put() Update the value in Hashmap in Java using When we want to HashMap inser
Difference between hashmap and map in Java
Publish Date:2025/04/14 Views:193 Category:Java
-
This tutorial explains the key differences between Map and in Java HashMap . In Java, Map is an interface for storing data in key-value pairs, and HashMap is Map an implementation class of the interface. Java has several classes ( TreeHashM
Get user home directory in Java
Publish Date:2025/04/14 Views:161 Category:Java
-
This tutorial explains how to get the user's home directory in Java and lists some sample code to guide you through the topic. For a multi-user operating system, each user has a file system directory; this directory is called the user's hom
Difference between size and length in Java
Publish Date:2025/04/14 Views:114 Category:Java
-
This tutorial explains the difference between size and length in Java. We have also listed some sample codes to help you understand the topic. Java has a size() method and a length property. Beginners may think that they are interchangeable
Mutex Locks in Java
Publish Date:2025/04/14 Views:198 Category:Java
-
In the field of computer science, mutual exclusion or mutex is known as the property of concurrency control. Every computer uses a minimum sequence of program instructions called a thread. At a time, the computer works on one thread. For be
How to compare characters for equality in Java
Publish Date:2025/04/14 Views:128 Category:Java
-
This tutorial shows you how to check if two characters are equal in Java. In Java, we can use the equals( == ) operator or the Character compare() equals() method of the Character class to compare two characters. If you are working with pri
Compile multiple Java files with a single command in Java
Publish Date:2025/04/14 Views:192 Category:Java
-
This tutorial explains how to compile multiple java files using a single command in Java. Compilation is a term used to refer to the process of converting java source code into bytecode using JDK. To execute any Java file, we need to follow
Arrow operator in Java ->
Publish Date:2025/04/14 Views:113 Category:Java
-
This tutorial explains - the role of the arrow operator ( ) in Java and lists some sample code to understand the topic. In Java 8, a new feature lambda expression was added, and the arrow operator appeared in Java to form lambda expressions