hashmap的按值排序
具体思路,
将hashmap的entry放到List中去,然后按照List的比较器进行排序,之后再把entry放到Linkedhashmap中去。
这里几个概念,首先hashmap是没有顺序的,所以没有办法进行排序,而之所以要放到List中去,是因为List可以比较方便的进行排序,这里用到了Map中的Entry,这个可以就单纯的简单的理解成<key,value>这样的一种数据结构,如此便比较好理解。对List进行排序之后,便有了顺序,然后这里使用Linkedhashmap是因为它是有顺序的,只不过它的顺序是按照数据放入的先后顺序来排序的。从而最终的map是一个有着大小顺序的map。
public Map<Integer,Integer> sortByValue(Map<Integer,Integer> map){
//按值排序的常见思路,将map中的entry放到list中,对list的entry通过比较器按值排序,然后将排序后的entr放到linkedhashmap中
//map.entry是map中的一个接口,就可以直接理解成包含key和value的一个javabean
List<Map.Entry<Integer,Integer>> list = new LinkedList<>(map.entrySet());//放到list中去
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {//进行排序
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return (o2.getValue().compareTo(o1.getValue()));
}
});
Map<Integer,Integer> temp = new LinkedHashMap<>();//放入LinkedHashMap
for(Map.Entry<Integer,Integer> each:list){
temp.put(each.getKey(),each.getValue());
}
return temp;
}
Map的数据存入以及修改
当使用map的时候,有时候会遇到这样的场景,需要存入新数据,或需要对老数据进行更新。当然这里先进行判断,是否含有这个key,然后再分类进行输入。例如:
for(int i =0;i<nums.length;i++){
if(map.containsKey(nums[i])){
int value = map.get(nums[i]);
map.put(nums[i],value+1);
}
else {
map.put(nums[i],1);
}
}
但是明显这样比较麻烦,当我们的输入操作比较单一时,其实就不用这样麻烦,直接一行代码就完成了。例如:
for(int num:nums){
map.put(num,map.getOrDefault(num,0)+1);
}
这里的Map.getOrDefault(key,default value)意味,若有key,则返回其值,若无,则返回我们设置的默认值,这样就舒服多了,其实想也知道,这个方法也就是对key有无进行判断操作进行了一个封装而已。