对map的值进行排序


package com.asp;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class MapUtil {
    /**
     * 按map的value升序排序
     * 
     * @param map
     * @param top
     *          
     * @return
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueAsc(
            Map<K, V> map, int top) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
                map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

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

    /**
     * 按map value降序排序
     * 
     * @param map
     * @param top
     *     
     * @return
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDesc(
            Map<K, V> map, int top) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
                map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });

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

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

        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());
    }
}

优质内容筛选与推荐>>
1、Qt入门(12)——Qt国际化
2、Spring常用的Listener
3、day 09 初识函数(后面有很多天都在接触函数)
4、Mysql安装教程
5、ios 时间戳 当前时间 相互转化


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号