自定义Map.Entry的Comperator实现字符频率降序排序
leetCode (#451,middle) java实现
class Solution { public String frequencySort(String s) { Map<Character,Integer> map = new HashMap<>(); //放入map for(char c :s.toCharArray()){ if(map.containsKey(c)){ map.put(c,map.get(c)+1); }else map.put(c,1); } //根据value的大小排序 Comparator<Map.Entry<Character,Integer>> comparator = new Comparator<Map.Entry<Character, Integer>>() { @Override public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) { return o2.getValue() - o1.getValue(); } }; //放入链表 List<Map.Entry<Character,Integer>> list = new ArrayList<>(map.entrySet()); //根据实现的comp排序 Collections.sort(list,comparator); //定义数组 StringBuilder sb = new StringBuilder(); for(Map.Entry<Character,Integer> entry : list){ for(int i = 0 ; i < entry.getValue();i++){ sb.append(entry.getKey()); } } return sb.toString(); } }