public static void main(string args)
//使用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);
}
參考這位老哥使用stream流對map按照value排序後使用linkedhashmap儲存,控制台輸出的值也是排好序的,返回前端後一看,竟然又無序了。
經過一番排查後發現是阿里的fastjson在序列化時對linkedhashmap進行了重排序,導致原本儲存的插入順序被打亂。
處理方式:遍歷map取值,拼接成字串,或者使用實體類儲存key和value,封裝成arraylist返回引數。import com.alibaba.fastjson.annotation.jsonfield;
@jsonfield(name = "map")
private linkedhashmap map;
C 中實現對map按照value值進行排序
map的兩個值分別為key值和value值,map是按照key值進行排序的,但有時候需要按照value值進行排序,並且按照value的順序輸出key值,排序 如下 typedef pairpair int cmp const pair x,const pair y mapm vectorvec fo...
Map分別按照Key和value排序
讀取檔案,按照檔案內容中,名字出現的次數排序輸出,關鍵點在於map按照value排序,這篇文章有詳細的描述.value排序 public class stringsort catch filenotfoundexception e catch ioexception e list maplist n...
Map基於Value值排序
方法1 使用treemap,可以參考下面的代 public class testing class valuecomparator implements comparator note this comparator imposes orderings that are inconsistent w...