1.传统排序:
//对值进行排序,此处为降序
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map)
{
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
{
int compare = (o1.getValue()).compareTo(o2.getValue());
return -compare;
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
2.新排序方法:
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean asc)
{
Map<K, V> result = new LinkedHashMap<>();
Stream<Entry<K, V>> stream = map.entrySet().stream();
if (asc) //升序
{
//stream.sorted(Comparator.comparing(e -> e.getValue()))
stream.sorted(Map.Entry.<K, V>comparingByValue())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
else //降序
{
//stream.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
stream.sorted(Map.Entry.<K, V>comparingByValue().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
public static <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map, boolean asc)
{
Map<K, V> result = new LinkedHashMap<>();
Stream<Entry<K, V>> stream = map.entrySet().stream();
if (asc)
{
stream.sorted(Map.Entry.<K, V>comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
else
{
stream.sorted(Map.Entry.<K, V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
3.上面的知识点补充:
jdk1.8新特性:
a. 新增Lambda表达式和函数式接口;
b. 新增Stream API(java.util.stream);
其他新特性见文章:https://blog.youkuaiyun.com/u014470581/article/details/54944384
---------------------------------------------欢迎关注公众号(生活不止有代码)-------------------------------------------------------