Map和Collections是同级别的,不能像List排序那样直接用Collections.sort(new Comparator<?>(){ 复写compara方法});
HashMap没有排序
TreeMap默认排序为升序,注意是按键值key排序
package com.swift; import java.util.Comparator; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class Scanner_String_ABCD_Times_jiangxu { public static void main(String[] args) { /* * 输入字符串,统计A、B、C、D、出现次数,由高到低输出字母和出现次数 */ Scanner scan=new Scanner(System.in); System.out.println("请输入一个字符串,用于统计A、B、C、D出现次数:"); String str=scan.nextLine(); //降序 Map<Character,Integer> map=new TreeMap<Character,Integer>(new Comparator<Character>() { @Override public int compare(Character arg0, Character arg1) { return arg1.compareTo(arg0); } }); map.put(‘A‘, 0); map.put(‘B‘, 0); map.put(‘C‘, 0); map.put(‘D‘, 0); map.put(‘a‘, 0); map.put(‘b‘, 0); map.put(‘c‘, 0); map.put(‘d‘, 0); char[] arr=str.toCharArray(); for(char c:arr) { if(map.containsKey(c)) { Integer i=map.get(c); i++; map.remove(c); map.put(c, i); } } for(Map.Entry<Character, Integer> entry:map.entrySet()) { System.out.println(entry.getKey()+"~~"+entry.getValue()); } for(Map.Entry<Character, Integer> entry:map.entrySet()) { System.out.println(entry.getKey()+"~~"+entry.getValue()); } } }
根据TreeMap的value来进行排序。对value排序还是需要借助于Collections的sort(List<T> list, Comparator<? super T> )
package com.swift; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; public class Scanner_String_ABCD_Times_jiangxu { public static void main(String[] args) { /* * 输入字符串,统计A、B、C、D、出现次数,由高到低输出字母和出现次数 */ Scanner scan=new Scanner(System.in); System.out.println("请输入一个字符串,用于统计A、B、C、D出现次数:"); String str=scan.nextLine(); Map<Character,Integer> map=new TreeMap<Character,Integer>(); map.put(‘A‘, 0); map.put(‘B‘, 0); map.put(‘C‘, 0); map.put(‘D‘, 0); map.put(‘a‘, 0); map.put(‘b‘, 0); map.put(‘c‘, 0); map.put(‘d‘, 0); char[] arr=str.toCharArray(); for(char c:arr) { if(map.containsKey(c)) { Integer i=map.get(c); i++; map.remove(c); map.put(c, i); } } //遍历 for(Map.Entry<Character, Integer> entry:map.entrySet()) { System.out.println(entry.getKey()+"~~"+entry.getValue()); } //把map.entrySet转换为list 用Collections.sort(list,new Comparator<>(){});排序 降序 List<Map.Entry<Character,Integer>> list=new ArrayList<Map.Entry<Character,Integer>>(map.entrySet());//不能把map.entrySet() cast to(强转) list,需要构造 Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>(){ @Override public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) { int i=o2.getValue()-o1.getValue(); return i; } }); //不要再遍历map,而要遍历已排序的list for(Map.Entry<Character, Integer> entry:list) { System.out.println(entry.getKey()+"~~"+entry.getValue()); } } }