根据map的key进行排序(倒序)
public <K extends Comparable<? super K>, V > Map<K, V>
sortByKey(Map<K,V>map){
Map<K,V> result = new LinkedHashMap<>();
map.entrySet().stream().sorted(
Map.Entry.<K,V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(),e.getValue()));
return result;
}
根据map的key进行排序(升序)
public <K extends Comparable<? super K>, V > Map<K, V>
sortByKey(Map<K,V>map){
Map<K,V> result = new LinkedHashMap<>();
map.entrySet().stream().sorted(
Map.Entry.<K,V>comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(),e.getValue()));
return result;
}

博客给出了使用Java8 Stream操作对Map根据key进行排序的代码示例,包含倒序和升序两种排序方式。通过Stream的sorted方法结合Map.Entry的comparingByKey方法实现排序,并将结果存入LinkedHashMap中。
1805

被折叠的 条评论
为什么被折叠?



