这是一道面试题,也是java基础体现的一个题目。
题目要求:
有一个输入字符串,例如:String s=”welcome to ***”. 词中间有空格, 请统计每个词出现的次数,并按出现次数多少排序输出。
以下代码分别是两种方法实现:
public class Demo {
public static void main(String[] args) {
String s = "welcome to rds";
method1(s);
method2(s);
}
//方法一
public static void method1(String s) {
Integer count;
Map<Character, Integer> map = new HashMap<>();
List<Map.Entry<Character, Integer>> list = new ArrayList<>();
// 拆分字符串,统计字符个数
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
count = map.get(ch);
if (count == null) {
map.put(ch, 1);
} else {
map.put(ch