和力扣 692. 前K个高频单词 相同

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) {
        // write code here
        Map<String, Integer> map = new HashMap<>();
        for (String s : strings) map.put(s, map.getOrDefault(s, 0) + 1);
        
        List<String> list = new ArrayList<>();
        for (String s : map.keySet()) list.add(s);
        
		//简便写法	
		list.sort((String s1, String s2) -> {
            return map.get(s1) == map.get(s2) ? s1.compareTo(s2)	//字典序升序
                : map.get(s2) - map.get(s1);	//频率降序
        });

        String[][] res = new String[k][2];
        for (int i = 0; i < k; i++) {
            String s = list.get(i);
            res[i][0] = s;
            res[i][1] = map.get(s) + "";
        }
        
        return res;
    }
}