题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.Scanner; import java.util.*; import java.util.stream.Collectors; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); countStr(str); } public static void countStr(String input) { Map<Character, Integer> map = new HashMap<>(); char[] chars = input.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } mapSort(map); } public static void mapSort(Map<Character, Integer> map) { List<StrCountSortVO> list = new ArrayList<>(); map.forEach((k, v)-> { StrCountSortVO strCountSortVO = new StrCountSortVO(k, v); list.add(strCountSortVO); }); List<StrCountSortVO> result = list.stream().sorted(Comparator.comparing( StrCountSortVO::getCount).reversed() .thenComparing(StrCountSortVO::getStr) ).collect(Collectors.toList()); for (StrCountSortVO strCountSortVO : result) { System.out.print(strCountSortVO.str); } } } class StrCountSortVO { public Character str; public Integer count; StrCountSortVO( Character str, Integer count) { this.str = str; this.count = count; } public Character getStr() { return str; } public Integer getCount() { return count; } }