TreeMap可以用于排序,通过自定义比较器对TreeMap进行排序
import java.util.*;
public class Solution {
/**
* return topK string
* @param strings string字符串一维数组 strings
* @param k int整型 the k
* @return string字符串二维数组
*/
public String[][] topKstrings (String[] strings, int k) {
Map<String, Integer> map = new TreeMap<>();
for (String str : strings) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
if (o1.getValue().equals(o2.getValue())) {
return o1.getKey().compareTo(o2.getKey());
} else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
String[][] ans = new String[k][2];
int i = 0;
for (Map.Entry<String, Integer> entry : entryList) {
if (i < k) {
ans[i][0] = entry.getKey();
ans[i][1] = entry.getValue().toString();
i++;
}
}
return ans;
}
}