English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Programmation Orientée Objet (I)

Java Programmation Orientée Objet (II)

Java Programmation Orientée Objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map Collection

Java Set Collection

Java Entrée/Sortie (I/O)

Java Reader/Writer

Autres sujets Java

Programme Java pour trier une carte par valeur

Comprehensive Java examples

Dans ce programme, vous apprendrez à trier une carte donnée par valeur en Java.

Exemple : trier une carte par valeur

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.

Comprehensive Java examples