标签:ide lse 字符 contains int arraylist integer cte dem
最近在面试,好多的面试题,笔试题,有的笔试题搜百度搜不到点子上的
这个刚开始看着很简单,后面说要排序,想起了用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]
给定一个字符串,打印输出有重复的字符和重复的次数,并且按照重复的次数升序输出
标签:ide lse 字符 contains int arraylist integer cte dem
原文地址:https://www.cnblogs.com/cmmplb/p/11963518.html