map 键值对按V排序
map 键值对按V排序方法有很多,简单介绍几种:推荐最后一种
-
map直接遍历,比较V的值,从最大或最小的,依次存入一个新的map集合,这种方法逻辑简单,弊端也很明显,代码量会很多,而且会生成新的集合,占用空间;
-
重写Comparator的compare方法,我在未使用jdk1.8前使用
// Map的value值降序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(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> returnMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
- jdk1.8的stream,数据流,代码量少,也易于理解,有时候会报错,需要进行类型转换
代码如下:
package com.ab.sort;
import java.util.HashMap;
import org.junit.Test;
/**
* @author ab 2019年5月5日
*/
public class SortMap {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 5);
map.put("s", 4);
map.put("d", 56);
map.put("f", 2);
map.put("q", 7);
System.out.println(map);
map.entrySet().stream().sorted((x, y) -> (x.getValue() - y.getValue()))
.forEach(System.out::println);
}
@Test
public void test() {
HashMap<String, Double> map = new HashMap<String, Double>();
map.put("a", 5.0);
map.put("s", 4.0);
map.put("d", 56.0);
map.put("f", 2.0);
map.put("q", 7.0);
System.out.println(map);
map.entrySet().stream().sorted((x, y) -> (x.getValue() - y.getValue()))
.forEach(System.out::println);
}
}