English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to sort a given mapping by value in Java.
import java.util.*; public class SortMap { public static void main(String[] args) { 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"); Map<String, String> result = sortMap(capitals); for (Map.Entry<String, String> entry : result.entrySet()) { System.out.print("Key: ", + entry.getKey()); System.out.println(" Value: ", + entry.getValue()); } } public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) { List<Map.Entry<String, String>> capitalList = new LinkedList<>(map.entrySet()); Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2); LinkedHashMap<String, String> result = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : capitalList) { result.put(entry.getKey(), entry.getValue()); } return result; } }
When running the program, the output is:
Key: Australia Value: Canberra Key: Nepal Value: Kathmandu Key: England Value: London Key: India Value: New Delhi Key: United States Value: Washington
In the above program, we convert the LinkedHashMap country/The regions and their respective capitals are stored in the variable capitals.
We have a method sortMap() that takes a doubly linked list and returns a sorted doubly linked list.
Within the method, we convert the hash map to a list capitalList. Then, we use the sort() method, which accepts a list and a comparator.
In our instance, the comparator is (o1,o2)-> o1.getValue().compareTo(o2.getValue()) two lists o1and o2lambda expression for comparing the values.
After the operation, we get the sorted list capitalList. Then, we simply convert the list to a LinkedHashMap result and return it.
Returning to the main() method, we iterate over each item in the map and print its key and value.