自定义排序
public class Solution {
/**
* return topK string
* @param strings string字符串一维数组 strings
* @param k int整型 the k
* @return string字符串二维数组
*/
public String[][] topKstrings (String[] strings, int k) {
// write code here
int len = strings.length;
String[][] res = new String[k][2];
if (len == 0|| strings == null){
return res;
}
HashMap<String,Integer> map = new HashMap<>();
for (int i = 0; i < len; i++) {
String str = strings[i];
map.put(str,map.getOrDefault(str,0)+1);
}
// Arrays.sort(map,new Comparator<String,Integer>(HashMap o1) );
ArrayList<Map.Entry<String, Integer>> list =
new ArrayList<>(map.entrySet());
// 先是按出现次数降序比较,相同则再按照字符ASCII码降序比较
Collections.sort(list,
(o1, o2) ->
(o1.getValue().compareTo(o2.getValue()) ==
0 ? o1.getKey().compareTo(o2.getKey()) :
o2.getValue().compareTo(o1.getValue()))
);
for (int i = 0; i < k; i++) {
res[i][0] = list.get(i).getKey();
res[i][1] = String.valueOf(list.get(i).getValue());
}
return res;
}
}