最近在面试,好多的面试题,笔试题,有的笔试题搜百度搜不到点子上的
这个刚开始看着很简单,后面说要排序,想起了用Collections里面自定义的比较器
代码:
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]
原文地址:https://www.cnblogs.com/cmmplb/p/11963518.html
时间: 2024-10-11 06:36:25