English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à trier une carte donnée par valeur en Java.
import java.util.*; public class SortMap { public static void main(String[] args) { LinkedHashMap<String, String> capitals = new LinkedHashMap<>(); capitals.put("Népal", "Katmandou"); capitals.put("Inde", "New Delhi"); capitals.put("États-Unis", "Washington"); capitals.put("Angleterre", "Londres"); capitals.put("Australie", "Canberra"); Map<String, String> result = sortMap(capitals); for (Map.Entry<String, String> entry : result.entrySet()) { System.out.print("Clé: ", + entry.getKey()); System.out.println(" Valeur: ", + 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,o -> o1> o2); LinkedHashMap<String, String> result = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : capitalList) { result.put(entry.getKey(), entry.getValue()); } return result; } }
Lors de l'exécution de ce programme, la sortie est :
Clé: Australie Valeur: Canberra Clé: Népal Valeur: Katmandou Clé: Angleterre Valeur: Londres Key: India Value: New Delhi 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.
Inside the method, we convert the hash map to a list capitalList. Then, we use the sort() method, which accepts a list and a comparator.1In our instance, the comparator is (o2,o-)1> o2.getValue().compareTo(o1.getValue()) two lists o2and o
The lambda expression used to compare the values.
After the operation, we get the sorted list capitalList. Then, we just need to convert the list to a LinkedHashMap result and return it.