我们经常遇到需要对Map排序的情况,一般根据key排序可以使用TreeMap来保存即可自动排序。那么问题来了,如果需要根据value排序呢,怎么实现?
如题:给定一个字符串数组,输出出现频率最高的k个词,如果出现频率相同,按字典序排序。
分析:
分三步走,1)统计出现频率,使用Map,key为单词,value为出现频率,2)根据频率从大到小排序,3)输出频率topk的单词
话不多说,上代码
public static void printTopK(String[] arr,int k){
Map<String,Integer> map=new HashMap<>();
//统计次数
for (String word:arr){
if (map.containsKey(word)) {
int count = map.get(word);
map.put(word, count+1);
}else {
map.put(word,1);
}
}
//排序,转List,重写compare方法,也可以用lamda表达式写
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
//或 list.sort((o1, o2) -> o2.getValue() - o1.getValue());
//输出
for (int i=0;i<k;i++){
System.out.println(list.get(i).getKey());
}
}
}
来源:CSDN
作者:流言丶飞羽
链接:https://blog.csdn.net/u011345756/article/details/103543725