/*** 统计一个字符串中每个字符出现的次数,保存到HashMap集合中* * 对HashMap集合中的数据进行降序排序** @author Mac* @date 2020年8月11日 上午10:30:34*/
public class 练习_list排序 {public static void main(String[] args) {String str = "asdfjk2348aaaauj;sdjf89234-8-asjsf";HashMap<String, Integer> map = new HashMap<>();for (int i = 0; i < str.length(); i++) {String c = str.charAt(i) + "";map.put(c, map.containsKey(c) ? map.get(c) + 1 : 1);}System.out.println(map);// 获取所有键值对的集合Set<Entry<String, Integer>> entries = map.entrySet();// 将set集合转换为list集合ArrayList<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(entries);// 降序Collections.sort(list, new Comparator<Entry<String, Integer>>() {/*** 重写compare()方法,指定比较的方式* 升序:如果该对象大于、小于或等于指定对象,则分别返回正整数、负整数或零* 降序:如果该对象大于、小于或等于指定对象,则分别返回负整数、正整数或零*/@Overridepublic int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {if (o1.getValue() > o2.getValue()) {return -1;} else if (o1.getValue() < o2.getValue()) {return 1;}return 0;}});System.out.println(list);}
}