使用了HashMap来记录字母出现的次数。
/** * @Author: Administrator * @Date: 2021/9/26 17:53 * @Description: */ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] arg) { Scanner scan = new Scanner(System.in); StringBuilder builder = new StringBuilder(); while (scan.hasNext()) { String input = scan.nextLine(); char[] charArr = input.toCharArray(); Map<String, Integer> map = new HashMap<>(); for (char charecter : charArr) { String charStr = String.valueOf(charecter); if (map.containsKey(charStr)) { map.put(charStr, map.get(charStr) + 1); } else { map.put(charStr, 1); } } //这里将map.entrySet()转换成list List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); //然后通过比较器来实现排序 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { //升序排序 public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue())==0? (int)o2.getKey().charAt(0)- (int)o1.getKey().charAt(0): o1.getValue().compareTo(o2.getValue()); } }.reversed()); for (Map.Entry<String, Integer> mapping : list) { builder.append(mapping.getKey()); } builder.append("\n"); } System.out.println(builder); } }