可优化,遍历一遍字符串即可,用数组代替map

import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        char[] chars = s.toCharArray();
        HashMap<Character, Integer> map = new HashMap<>();
        for(int i = 0; i < chars.length; i++){
            if(map.containsKey(chars[i])){
                map.put(chars[i], map.get(chars[i]) + 1);
            }else{
                map.put(chars[i], 1);
            }
        }
        int temp = 'a';
        StringBuilder res = new StringBuilder();
        for(int i = 0; i < 26; i++){
            char ch = (char) temp;
            if(map.containsKey(ch)){
                res.append(ch).append(map.get(ch));
            }
            temp++;
        }
        System.out.println(res);
    }
}