1)map排序方法:
/**
* map排序
* @param map 要排序的目标数组
* @param isKey 是否是按key进行排序
* @param isDesc 是否是降序
* @param <K>
* @param <V>
* @return
*/
public <K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> sortMap(Map<K, V> map, boolean isKey, boolean isDesc) {
Map<K, V> result = new LinkedHashMap<>();
if (isKey) {
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
} else {
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())//根据value降序排序
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream()
.sorted(Map.Entry.<K, V>comparingByValue()//根据value升序排序
).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
}
2)测试
//对map集合进行排序
@Test
public void test3() {
Map<Integer, Double> map = new HashMap<>();
map.put(1, 2.0d);
map.put(2, 1.0d);
map.put(3, 4.5d);
map.put(4, 2.3d);
Map<Integer, Double> map1 = sortMap(map, true, false);
System.out.println(map1);
}
第一个方法,是使用参数控制是否是根据map的key进行排序还是升序降序,下面是单独使用根据map的key进行排序,或者是根据map的value进行排序
测试可自行测试,传入map集合就可进行排序
3)根据map的key进行排序
//根据key对map进行排序
public <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isDesc) {
Map<K, V> result = new LinkedHashMap<>();
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey())
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
4)根据map的value进行排序
//根据value对map集合进行排序
public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean isDesc) {
Map<K, V> result = new LinkedHashMap<>();
if (isDesc) {
map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())//根据value降序排序
.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
map.entrySet().stream()
.sorted(Map.Entry.<K, V>comparingByValue()//根据value升序排序
).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}
5)获取第一个元素的key
//取map集合中的第一个元素的key值
private Object getKeyOrNull(Map<Integer, Double> map) {
Object obj = null;
for (Map.Entry<Integer, Double> entry : map.entrySet()) {
obj = entry.getKey();
if (obj != null) {
break;
}
}
return obj;
}
可按需进行修改优化