The Map interface also provides methods for checking the presence of a key, getting the size of the Map, and iterating over the Map to process its key-value pairs.
Map is a generic interface, declared as Map<K, V>.
A Map cannot contain duplicate keys. Each key can map to at most one value.
To know more about Java Program to Sort map by Values read the complete article.
Steps for Program to Sort a Map By Values:
Convert the Map into a Stream.
Sort the stream using the sorted method with a custom Comparator that compares the Map values.
Collect the sorted stream into a new Map using the collect method and toMap collector with the original Map’s keys and values.
Return the newly sorted Map.
Java Map Interface:
Some common implementations of the Map interface include java.util.HashMap, java.util.TreeMap, and java.util.LinkedHashMap. Each implementation has different performance characteristics and use cases, but they all provide the same basic Map functionality.
Java LinkedHashMap:
java.util.Linked Java's HashMap class extends the java.util.HashMap class and implements the java.util.Map interface. To retain the order of the elements added into the map, it uses a doubly-linked list.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Alex", 50);
map.put("Bob", 60);
map.put("Charlie", 70);
map.put("David", 80);
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
System.out.println("Sorted Map by Values in Descending Order: " + list);
}
}
Output
Sorted Map by Values in Descending Order: [David=80, Charlie=70, Bob=60, Alex=50]
Explanation:
This code sorts a Map of by values in descending order. The List.sort method is used with the Map.Entry.comparingByValue method, and the reversed method is called on the result to sort the list in descending order. The sorted Map is represented as a List of Map.Entry objects and is printed as the output.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment