1.排序并取出前五个
public static void main(String[] args) throws Exception{
Map<String, Integer> hashMap = new HashMap<String, Integer>();
hashMap.put("1", 1);
hashMap.put("2", 2);
hashMap.put("3", 3);
hashMap.put("4", 4);
hashMap.put("5", 5);
List<String> list = hashMap.entrySet().stream()
.sorted((Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) -> o2.getValue() - o1.getValue())
.map(entry -> entry.getKey()).collect(Collectors.toList())
.subList(0, 5);
System.out.println(list);
}
//得到的是value逆序得到的key的序列
//.sorted,对map根据value排序
//.map方法把map的key转成set
//.subList取前n位,下图(0,5位)
//.retainAll(拿key-set,去与map碰撞),判断交集并覆盖之前的list,取出相交个
//list的value就是相交的 key,如需value取出即可
2.排序
List<Map.Entry<String, Integer>> list_Data = new ArrayList<Map.Entry<String,Integer>>(hashMap.entrySet());
//通过Collections.sort(List I,Comparator c)方法进行排序
Collections.sort(list_Data,new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
System.out.println(list_Data);
//Lambda
Collections.sort(list_Data,(o1, o2)-> {
o2.getValue() - o1.getValue()
});