上干货!
---]----------------------------------------------------------------------------------------------
题文要求:
/*分析以下需求,并用代码实现: (1)统计每个单词出现的次数 (2)有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔) (3)打印格式: to=3 think=1 you=2*/
----------------------------------------------------------------------------------------------------------------------
代码区:
import java.util.Comparator;
import java.util.TreeMap;
public class HomeWork04 {
public static void main(String[] args) {
String str = "If you want to change your fate I think you must come to the dark horse to learn java";
String[] arr = str.split(" ");
TreeMap<String, Integer> tm = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length()-o2.length()==0?o1.compareTo(o2):o1.length()-o2.length();
}
});
for (String string : arr) {
if (!tm.containsKey(string)) {
tm.put(string, 1);
} else {
tm.put(string, tm.get(string)+1);
}
}
for (String string : tm.keySet()) {
System.out.print(string+"="+tm.get(string)+" ");
}
}
}
-----------------------------------------------------------------------------------------------------------------------------
总结下:
这道题 就想统计 字符出现的次数一样,
只不过是将 正则的 法则 稍微变了一下,
那个是存 字符,
这个是存 字符串.原理都是一样的
都用到了 比较器.
|