Map 按照 key或者value进行排序成有序map,SortedMap

package com.wapwag.woss.common.utils;

import java.util.*;

public class MapUtil {
    /**
     * 按map的value升序排序
     *
     * @param map
     * @param top 排序后,取前top名
     *
     * @return
     */
    public static > Map sortByValueAsc(
            Map map, int top) {
        List> list = new LinkedList>(
                map.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) {
            if (top-- == 0) {
                break;
            }
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    /**
     * 按map value降序排序
     *
     * @param map
     * @param top 排序后,取前top名
     *
     * @return
     */
    public static > Map sortByValueDesc(
            Map map, int top) {
        List> list = new LinkedList>(
                map.entrySet());
        Collections.sort(list, new Comparator>() {
            public int compare(Map.Entry o1, Map.Entry o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });

        Map result = new LinkedHashMap();
        for (Map.Entry entry : list) {
            if (top-- == 0) {
                break;
            }
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    /**
     * 按key排序
     *
     * @param unsort_map
     * @return
     */
    public static SortedMap mapSortByKey(
            Map unsort_map) {
        TreeMap result = new TreeMap();

        Object[] unsort_key = unsort_map.keySet().toArray();
        Arrays.sort(unsort_key);

        for (int i = 0; i < unsort_key.length; i++) {
            result.put(unsort_key[i].toString(), unsort_map.get(unsort_key[i]));
        }
        return result.tailMap(result.firstKey());
    }


}

你可能感兴趣的:(java)