public static > Map sortByValue(Map map, boolean asc)
{
Map result = new LinkedHashMap<>();
Stream> stream = map.entrySet().stream();
if (asc) //升序
{
//stream.sorted(Comparator.comparing(e -> e.getValue()))
stream.sorted(Map.Entry.comparingByValue())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
else //降序
{
//stream.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
stream.sorted(Map.Entry.comparingByValue().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
public static , V > Map sortByKey(Map map, boolean asc)
{
Map result = new LinkedHashMap<>();
Stream> stream = map.entrySet().stream();
if (asc)
{
stream.sorted(Map.Entry.comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
else
{
stream.sorted(Map.Entry.comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}