善用stream流,大大减少代码量
import java.util.*; import java.util.function.Function; 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) { // write code here Map<String, Long> map = Arrays.stream(strings).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); List<String> list = Arrays.stream(strings).distinct().sorted(((o1, o2) -> map.get(o1).equals(map.get(o2)) ? o1.compareTo(o2) : map.get(o2).compareTo(map.get(o1)))).limit(k).collect(Collectors.toList()); String[][] res = new String[k][2]; for(int i = 0; i < k; i++){ res[i][0] = list.get(i); res[i][1] = String.valueOf(map.get(list.get(i))); } return res; } }