HashMap排序(按照key,按照value)

package com.lidl.com.lidl.web;
import java.util.*;

class TestMap2 {
    public static void main(String[] args) {
        Map map1 = new HashMap<>();
        map1.put(3, "三");
        map1.put(6, "六");
        map1.put(1, "一");

        Map map3 = new HashMap<>();
        map3.put(3, "三");
        map3.put(6, "六");
        map3.put(1, "一");

        Map map2 = new HashMap<>();
        map2.put("三", 3);
        map2.put("一", 1);
        map2.put("六", 6);

        Map map4 = new HashMap<>();
        map4.put("三", 3);
        map4.put("一", 1);
        map4.put("六", 6);

        sortByKey(map1);
        sortByKey(map4);
        sortByValue(map2);
        //sortByValue(map3);
    }

    // 按照键排序
    static void sortByKey(Map map) {
        Object[] objects = map.keySet().toArray();
        Arrays.sort(objects);
        for (int i = 0; i < objects.length; i++) {
            System.out.println("键:" + objects[i] + " 值:" + map.get(objects[i]));
        }
    }

    // 按照值排序
    static void sortByValue(Map map) {
        List> list = new ArrayList>(map.entrySet());
        Collections.sort(list, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });

        for (Map.Entry mapping : list) {
            System.out.println("键:" + mapping.getKey() + " 值:" + mapping.getValue());
        }
    }
}

 

你可能感兴趣的:(java)