Map排序工具类

package com.csf.sam.util;

import java.util.*;

/**
 * Created by fenglei.ma on 2018/4/23. 23:03
 */
public class CollectionTools {

    /**
     * 将map按照value值排序
     *
     * @param map
     * @param reverse true:倒序。false:正序。
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map sortByValue(Map map, final boolean reverse) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                if (reverse) {
                    return -((Comparable) ((Map.Entry) o1).getValue())
                            .compareTo(((Map.Entry) o2).getValue());
                }
                return ((Comparable) ((Map.Entry) o1).getValue())
                        .compareTo(((Map.Entry) o2).getValue());
            }
        });

        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext(); ) {
            Map.Entry entry = (Map.Entry) it.next();
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    /**
     * 将map按照key值排序
     *
     * @param map
     * @param reverse true:倒序。false:正序。
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map sortByKey(Map map, final boolean reverse) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                if (reverse) {
                    return -((Comparable) ((Map.Entry) o1).getKey())
                            .compareTo(((Map.Entry) o2).getKey());
                }
                return ((Comparable) ((Map.Entry) o1).getKey())
                        .compareTo(((Map.Entry) o2).getKey());
            }
        });

        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext(); ) {
            Map.Entry entry = (Map.Entry) it.next();
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }


    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(1, 1);
        map.put(3, 3);
        map.put(2, 2);

        Map result = sortByKey(map, true);
        System.out.println(result);
        System.out.println(result.keySet());

        List<Integer> list = new ArrayList<Integer>();
        list.addAll(result.keySet());
        System.out.println(list);
    }
}

 

posted @ 2018-04-24 14:14  百合叶  阅读(117)  评论(0编辑  收藏  举报