In recent interviews, face a lot of questions, questions the pen, pen some questions search Baidu search not the point of
The beginning looked very simple, say you want to sort later, remembering the comparator inside with a custom Collections
Code:
public class StringDemo { public static void main(String[] args) { String str = "asdzxasdqweasdzs"; char[] chars = str.toCharArray(); Map<Character, Integer> map = new HashMap<>(); for (char ch : chars) { if (map.containsKey(ch)) { map.put(ch, map.get(ch) + 1); } else { map.put(ch, 1); } } System.out.println("map:" + map); //排序 List<Map.Entry<Character, Integer>> list = new ArrayList<>(); for (Map.Entry<Character, Integer> entry : map.entrySet()) { list.add(entry); } Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() { @Override public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) { return o1.getValue() - o2.getValue(); } }); System.out.println("排序后:" + list); } } 结果: map:{a=3, q=1, s=4, d=3, e=1, w=1, x=1, z=2} 排序后:[q=1, e=1, w=1, x=1, z=2, a=3, d=3, s=4]