Comment trier une carte en Java

Comment trier une carte en Java

Peu d'exemples Java pour trier une carte par ses clés ou ses valeurs.

Note
Si vous utilisez Java 8, reportez-vous à cet article -How to use Stream APIs to sort a Map

1. Trier par clé

1.1 Uses java.util.TreeMap, it will sort the Map by keys automatically.

SortByKeyExample1.java

package com.example.test;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortByKeyExample1 {

    public static void main(String[] args) {

        Map unsortMap = new HashMap();
        unsortMap.put("Z", "z");
        unsortMap.put("B", "b");
        unsortMap.put("A", "a");
        unsortMap.put("C", "c");
        unsortMap.put("D", "d");
        unsortMap.put("E", "e");
        unsortMap.put("Y", "y");
        unsortMap.put("N", "n");
        unsortMap.put("J", "j");
        unsortMap.put("M", "m");
        unsortMap.put("F", "f");

        System.out.println("Unsort Map......");
        printMap(unsortMap);

        System.out.println("\nSorted Map......By Key");
        Map treeMap = new TreeMap(unsortMap);
        printMap(treeMap);

    }

    //pretty print a map
    public static  void printMap(Map map) {
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey()
                + " Value : " + entry.getValue());
        }
    }

}

Sortie

Unsort Map......
Key : A Value : a
Key : B Value : b
Key : C Value : c
Key : D Value : d
Key : E Value : e
Key : F Value : f
Key : Y Value : y
Key : Z Value : z
Key : J Value : j
Key : M Value : m
Key : N Value : n

Sorted Map......By Key
Key : A Value : a
Key : B Value : b
Key : C Value : c
Key : D Value : d
Key : E Value : e
Key : F Value : f
Key : J Value : j
Key : M Value : m
Key : N Value : n
Key : Y Value : y
Key : Z Value : z

1.2 Yet another java.util.TreeMap example, provide a custom Comparator to sort the key in descending order.

SortByKeyExample2.java

package com.example.test;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortByKeyExample2 {

    public static void main(String[] args) {

        Map unsortMap = new HashMap();
        unsortMap.put(10, "z");
        unsortMap.put(5, "b");
        unsortMap.put(6, "a");
        unsortMap.put(20, "c");
        unsortMap.put(1, "d");
        unsortMap.put(7, "e");
        unsortMap.put(8, "y");
        unsortMap.put(99, "n");
        unsortMap.put(50, "j");
        unsortMap.put(2, "m");
        unsortMap.put(9, "f");

        System.out.println("Unsort Map......");
        printMap(unsortMap);

        System.out.println("\nSorted Map......By Key");
        Map treeMap = new TreeMap(
                new Comparator() {

                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o2.compareTo(o1);
                    }

                });

        /* For Java 8, try this lambda
        Map treeMap = new TreeMap<>(
                        (Comparator) (o1, o2) -> o2.compareTo(o1)
                );
        */
        treeMap.putAll(unsortMap);

        printMap(treeMap);

    }

    public static  void printMap(Map map) {
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey()
                + " Value : " + entry.getValue());
        }
    }

}

Sortie

Unsort Map......
Key : 1 Value : d
Key : 50 Value : j
Key : 2 Value : m
Key : 99 Value : n
Key : 20 Value : c
Key : 5 Value : b
Key : 6 Value : a
Key : 7 Value : e
Key : 8 Value : y
Key : 9 Value : f
Key : 10 Value : z

Sorted Map......By Key
Key : 99 Value : n
Key : 50 Value : j
Key : 20 Value : c
Key : 10 Value : z
Key : 9 Value : f
Key : 8 Value : y
Key : 7 Value : e
Key : 6 Value : a
Key : 5 Value : b
Key : 2 Value : m
Key : 1 Value : d

2. Trier par valeur

Convertit leMap en unList<Map>, trie lesList<Map> avec unComparator personnalisé et le place dans une nouvelle mappe d'ordre d'insertion -LinkedHashMap

Map ---> List ---> Collections.sort() --> List (Sorted) ---> LinkedHashMap

SortByValueExample1.java

package com.example.test;

import java.util.*;

public class SortByValueExample1 {

    public static void main(String[] args) {

        Map unsortMap = new HashMap();
        unsortMap.put("z", 10);
        unsortMap.put("b", 5);
        unsortMap.put("a", 6);
        unsortMap.put("c", 20);
        unsortMap.put("d", 1);
        unsortMap.put("e", 7);
        unsortMap.put("y", 8);
        unsortMap.put("n", 99);
        unsortMap.put("j", 50);
        unsortMap.put("m", 2);
        unsortMap.put("f", 9);

        System.out.println("Unsort Map......");
        printMap(unsortMap);

        System.out.println("\nSorted Map......By Value");
        Map sortedMap = sortByValue(unsortMap);
        printMap(sortedMap);

    }

    private static Map sortByValue(Map unsortMap) {

        // 1. Convert Map to List of Map
        List> list =
                new LinkedList>(unsortMap.entrySet());

        // 2. Sort list with Collections.sort(), provide a custom Comparator
        //    Try switch the o1 o2 position for a different order
        Collections.sort(list, new Comparator>() {
            public int compare(Map.Entry o1,
                               Map.Entry o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
        Map sortedMap = new LinkedHashMap();
        for (Map.Entry entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        /*
        //classic iterator example
        for (Iterator> it = list.iterator(); it.hasNext(); ) {
            Map.Entry entry = it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }*/


        return sortedMap;
    }

    public static  void printMap(Map map) {
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey()
                    + " Value : " + entry.getValue());
        }
    }

}

Sortie

Unsort Map......
Key : a Value : 6
Key : b Value : 5
Key : c Value : 20
Key : d Value : 1
Key : e Value : 7
Key : f Value : 9
Key : y Value : 8
Key : z Value : 10
Key : j Value : 50
Key : m Value : 2
Key : n Value : 99

Sorted Map......By Value
Key : d Value : 1
Key : m Value : 2
Key : b Value : 5
Key : a Value : 6
Key : e Value : 7
Key : y Value : 8
Key : f Value : 9
Key : z Value : 10
Key : c Value : 20
Key : j Value : 50
Key : n Value : 99

2.2 Upgrade the above sortByValue() method to support generics.

    public static > Map sortByValue(Map unsortMap) {

        List> list =
                new LinkedList>(unsortMap.entrySet());

        Collections.sort(list, new Comparator>() {
            public int compare(Map.Entry o1, Map.Entry o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        Map result = new LinkedHashMap();
        for (Map.Entry entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }

        return result;

    }

Mettre à jour l'historique

  1. 7 juillet 2010 - Première ébauche.

  2. 8 juillet 2014 - Ajoutez d'autres exemples et corrigez les fautes de frappe.

  3. 12 août 2016 - Ajoutez une méthode générique, reformatez le code, corrigez les fautes de frappe et réécrivez du contenu.