Java的Map排序

排序实现正序,逆序和限定取数数量(前几位)

/**
 * @author ZengL
 * @description
 * @since 2024/7/29
 */
public class ComCollectionUtil {

    /**
     * map排序取限定数量
     *
     * @param map   排序map
     * @param asc   是否升序
     * @param limit 限定数量
     * @param <K>   键
     * @param <V>   值
     * @return 数据(排序取值后的新map)
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortMap(Map<K, V> map, boolean asc, Integer limit) {
        List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
        list.sort((o1, o2) -> {
            int compare = (o1.getValue()).compareTo(o2.getValue());
            if (asc) {
                return compare;
            } else {
                return -compare;
            }
        });
        if (ObjectUtil.isNotNull(limit)) {
            list = list.subList(0, limit);
        }
        Map<K, V> returnMap = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            returnMap.put(entry.getKey(), entry.getValue());
        }
        return returnMap;
    }

    public static void main(String[] args) {
        Map<String, Long> stringLongMap = new HashMap<>(15);
        stringLongMap.put("111", 111L);
        stringLongMap.put("222", 222L);
        stringLongMap.put("333", 333L);
        stringLongMap.put("444", 444L);
        stringLongMap.put("555", 555L);
        stringLongMap.put("666", 666L);
        stringLongMap.put("777", 777L);
        stringLongMap.put("888", 888L);
        stringLongMap.put("999", 999L);
        Map<String, Long> stringIntegerMap = sortMap(stringLongMap, true, 5);
        Map<String, Long> stringIntegerMap1 = sortMap(stringLongMap, false, 5);
        System.out.println(new ArrayList<>(stringIntegerMap.entrySet()));
        System.out.println(new ArrayList<>(stringIntegerMap1.entrySet()));

    }
}

输出

[111=111, 222=222, 333=333, 444=444, 555=555]
[999=999, 888=888, 777=777, 666=666, 555=555]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值