Map按照value值排序及踩坑

问题:使用stream流对map按照value排序后,再用LinkedHashMap存储,控制台打印的值是排好序的,返回前端后排序却被打乱了。

    public static void main(String[] args) {
        Map<String, Long> map = new HashMap<>();
        map.put("1", 232L);
        map.put("2", 1L);
        map.put("3", 6L);
        map.put("4", 34345L);
        map.put("5", 5436L);

//        //查看map内键值对集合的构造
//        Set<Entry<String, Long>> entries = map.entrySet();
//        Iterator<Entry<String, Long>> it = entries.iterator();
//        while (it.hasNext()) {
//            Entry<String, Long> next = it.next();
//            System.out.print(next.getKey() + "-");
//            System.out.println(next.getValue());
//        }

        //使用LinkedHashMap可以保留插入顺序,倒序则替换p1,p2位置
        LinkedHashMap resultMap = new LinkedHashMap();
        map.entrySet().stream()
            .sorted((p1, p2) -> p1.getValue().compareTo(p2.getValue()))
            .collect(Collectors.toList())
            .forEach(element -> resultMap.put(element.getKey(), element.getValue()));
        System.out.println(resultMap);
    }

排查:发现是阿里的fastjson在序列化时对LinkedHashMap进行了重排序,导致原本保存的插入顺序被打乱。

import com.alibaba.fastjson.annotation.JSONField;

@JSONField(name = "map")
private LinkedHashMap map;

处理方式:遍历map拼接key和value成字符串,或者使用实体类存储后,封装成List返回给前端。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值