题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
import java.util.Scanner; import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < str.length(); i++) { map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1); } List<Character> list = new ArrayList<>(map.keySet()); Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { Character ch1 = (Character) o1; Character ch2 = (Character) o2; if (map.get(ch1) > map.get(ch2)) { return -1; } else if (map.get(ch1) < map.get(ch2)) { return 1; } else { return ch1 - ch2; } } }); for(Character ch : list) { System.out.print(ch); } } }
这题两个地方的代码值得学习
1.在往map里put的时候,用map.getOrDefault(key, 0);这个方法可以省略掉判断key存不存在和往里put值的操作
2.在完成对map的赋值后,需要对按照value的大小对key进行排序时,先把map的keySet放入一个list,再重写Collection.sort的Comapare方法,按照value的大小进行降序排列,真的很优雅