Algorithm
-
Create a Map:
- Initialize a
Map
with the desired key-value pairs.
- Initialize a
-
Convert Map to List:
- Create a
List
ofMap.Entry
objects by using theentrySet()
method of theMap
.
- Create a
-
Sort the List:
- Implement a custom comparator to sort the list based on the values of the
Map.Entry
objects. - You can use the
Collections.sort()
method and provide the custom comparator.
- Implement a custom comparator to sort the list based on the values of the
-
Create a Sorted Map:
- Create a new
LinkedHashMap
to store the sorted entries.
- Create a new
-
Populate Sorted Map:
- Iterate through the sorted list and add each
Map.Entry
to the newLinkedHashMap
.
- Iterate through the sorted list and add each
-
Display or Use the Sorted Map:
- The new
LinkedHashMap
now contains entries sorted by values.
- The new
Code Examples
#1 Code Example- Java Programing Sort a map by values
Code -
Java Programming
import java.util.*;
import java.util.Map.Entry;
class Main {
public static void main(String[] args) {
// create a map and store elements to it
LinkedHashMap < String, String> capitals = new LinkedHashMap();
capitals.put("Nepal", "Kathmandu");
capitals.put("India", "New Delhi");
capitals.put("United States", "Washington");
capitals.put("England", "London");
capitals.put("Australia", "Canberra");
// call the sortMap() method to sort the map
Map < String, String> result = sortMap(capitals);
for (Map.Entry entry : result.entrySet()) {
System.out.print("Key: " + entry.getKey());
System.out.println(" Value: " + entry.getValue());
}
}
public static LinkedHashMap sortMap(LinkedHashMap map) {
List < Entry(map.entrySet());
// call the sort() method of Collections
Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue()));
// create a new map
LinkedHashMap < String, String> result = new LinkedHashMap();
// get entry from list to the map
for (Map.Entry entry : capitalList) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
Copy The Code &
Try With Live Editor
Output
Key: Australia Value: Canberra
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington
Demonstration
Java Programing Example to Sort a Map By Values-DevsEnv