问题:使用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返回给前端。