利用Comparator对HashMap按照value进行排序
给定一个字符串,按照字符出现次数,从大到小的顺序输出。对于英文字符,不区分大小写。
示例:
Aba12a,输出:Ab12
ABb1c,输出:Ba1c
import java.util.*; public class Main { public static void main(String[] args) { countStr("Aba12a"); countStr("ABb1c"); } public static void countStr(String s){ char[]arr=s.toCharArray(); //利用linkedHashMap LinkedHashMap<Character,Integer> map=new LinkedHashMap<>(); for(int i=0;i<arr.length;i++) { char temp=arr[i]; int temp_num=0+temp; if(temp_num>=97 && temp_num<=122)//是小写字母 { char daXie=(char)(temp_num-32); if(map.containsKey(temp)) //如果已经包含了小写字母 map.put(temp,map.get(temp)+1); else if(map.containsKey(daXie)) //如果已经包含了大写字母 map.put(daXie,map.get(daXie)+1); else map.put(temp,1); } else if(temp_num>=65 && temp_num<=90)//是大写字母 { char xiaoXie=(char)(temp_num-32); if(map.containsKey(temp)) //如果已经包含了大写字母 map.put(temp,map.get(temp)+1); else if(map.containsKey(xiaoXie)) //如果已经包含了小写字母 map.put(xiaoXie,map.get(xiaoXie)+1); else map.put(temp,1); } else //如果是其他字符 if(map.containsKey(temp)) map.put(temp,map.get(temp)+1); else map.put(temp,1); } //排序前输出 for(Character temp:map.keySet()) System.out.println(temp+"-"+map.get(temp)); //对哈希表进行排序 ArrayList<Map.Entry<Character,Integer>> list=new ArrayList<>(map.entrySet()); Collections.sort(list,new Comparator<Map.Entry<Character,Integer>>(){ @Override public int compare(Map.Entry<Character,Integer> o1,Map.Entry<Character,Integer> o2) { if(o1.getValue()>o2.getValue()) return -1; else if(o1.getValue()<o2.getValue()) return 1; else return 0; } }); System.out.println(); //排序后输出 // for(Map.Entry<Character,Integer> temp:list) // System.out.println(temp.getKey()+"-"+temp.getValue()); for(Map.Entry<Character,Integer> temp:list) System.out.print(temp.getKey()); System.out.println(); } }