Map集合练习
接着上一篇拓展题的答案
上一篇地址
要求
目标:输出一个字符串中每个字符出现的次数。值的次数排序,认可的!(经典面试题)
分析:
(1)键盘录入一个字符串。aabbccddaa123。
(2)定义一个Map集合,键是每个字符,值是其出现的次数。
(3)遍历字符串中的每一个字符。
(4)拿着这个字符去Map集合中看是否有这个字符键,有说明之前统计过,其值+1
没有这个字符键,说明该字符是第一次统计,直接存入“该字符=1”
提示:以下是本篇文章正文内容,下面案例可供参考
一、代码
// 1.定义一个扫描器,让用户输入字符串
Scanner sc = new Scanner(System.in);
System.out.print("请您输入字符串:");
String datas = sc.nextLine();
// 2.定义一个Map集合,键是每个字符,值是其出现的次数。
Map<Character, Integer> infos = new HashMap<>(); // {}
// 3.遍历datas字符串中的每个字符
// datas = aabbccddaa123
for (int i = 0; i < datas.length(); i++) {
// 当前字符
char ch = datas.charAt(i);
//4 拿着这个字符去Map集合中看是否有这个字符键,有说明之前统计过,其值+1
//没有这个字符键,说明该字符是第一次统计,直接存入“该字符=1”
if (infos.containsKey(ch)) {
// 存在该字符,之前统计过,其值+1
infos.put(ch, infos.get(ch) + 1);
} else {
// 不存在该字符串,说明该字符是第一次统计,直接存入“该字符=1”
infos.put(ch, 1);
}
}
// 5.输出结果。
System.out.println(infos);
//这是我为了好玩,这样写的
// 6.拓展需求:按照字符出现的次数大小降序排序
// List<String> listDatas = new ArrayList<>();
// infos.forEach((k , v) -> {
// listDatas.add(k+"="+v);
// });
// System.out.println(listDatas);
// Collections.sort(listDatas, new Comparator<String>() {
// @Override
// public int compare(String o1, String o2) {
// return Integer.valueOf(o2.split("=")[1]) - Integer.valueOf(o1.split("=")[1]) ;
// }
// });
// System.out.println(listDatas);
}
}