题解 | #字符串出现次数的TopK问题#
字符串出现次数的TopK问题
http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee
import java.util.*;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
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> countMap = new HashMap<>();
for(String s:strings){ // 统计每个字符串出现的个数
countMap.compute(s, (key, count) -> {
if(count==null) return 1;
return count+1;
});
}
return countMap.entrySet().stream()
.sorted((e1, e2) -> { // 排序
if(!e2.getValue().equals(e1.getValue())) // 按出现次数从大大小排序
return e2.getValue() - e1.getValue();
return e1.getKey().compareTo(e2.getKey()); // 次数相同则按字符串大小排序
}).limit(k) // 截取前k个
.map(e -> new String[]{e.getKey(), "" + e.getValue()}) // Map.Entry<K,V> -> String[]{K,V}
.collect(Collectors.toList()) // 汇集成List
.toArray(new String[0][2]); // 转为数组
}
}