淘先锋技术网

首页 1 2 3 4 5 6 7

Java 1.8 stream流 map<K,V>根据key 排序


//需要排序的map
Map<String,Object> map= new HashMap();

//降序
//创建空map 存储排序后 
Map<String,Object> sortMapDesc = new LinkedHashMap(map.size());
//加上reversed 倒序 ,正序去除
map.entrySet().stream()
   .sorted(Map.Entry.<String,List<Object>>comparingByKey().reversed())
   .forEachOrdered(e->sortMapDesc.put(e.getKey(),e.getValue()));

//升序
//创建空map 存储排序后 
Map<String,Object> sortMapAsc = new LinkedHashMap(map.size());
map.entrySet().stream()
   .sorted(Map.Entry.comparingByKey())
   .forEachOrdered(e->sortMapAsc.put(e.getKey(),e.getValue()));