11章-练习21-Map的使用


import java.util.*;

/**
* 练习21:通过使用Map<String,Integer>,遵循UniqueWords.java的形式来创建一个程序,它可以对一个文件中出现的单词计数。
* 使用带有第二个参数String.CASE_INSENSITIVE_ORDER的Collections.sort()方法对结果进行排序(将产生字母序),然后显示结果
*/
public class Exercise21 {

public static void main(String[] args) {

Map<String, Integer> map = new HashMap<String, Integer>();
List<String> wordList = new TextFile("SetOperations.java", "\\W+");
for (String word : wordList) {
map.put(word, map.get(word) == null ? 1 : map.get(word) + 1);
}
System.out.println(map);
List<String> sortKeyList = new ArrayList<>();
sortKeyList.addAll(map.keySet());
Collections.sort(sortKeyList, String.CASE_INSENSITIVE_ORDER);
for (String sortedKey : sortKeyList) {
System.out.print(sortedKey + ":" + map.get(sortedKey) + " ");
}
}
}
/* Output:
{com=2, added=2, SetOperations=2, main=1, String=5, Print=1, removeAll=1, java=4, split=3, from=2, Collections=4, HashSet=3, add=1, new=2, package=1, static=2, void=1, set2=11, in=4, contains=2, util=3, true=2, set1=23, A=4, B=4, Set=3, C=4, import=4, D=4, E=4, F=4, G=4, H=6, I=3, J=3, K=3, L=3, demo=2, M=4, N=3, remove=1, example=2, holding=1, public=2, Output=1, X=4, Y=4, Z=4, class="1", containsAll=2, false=2, elevensection=2, args=1, print=8, removed=2, addAll=3, to=2}
A:4 add:1 addAll:3 added:2 args:1 B:4 C:4 class:1 Collections:4 com:2 contains:2 containsAll:2 D:4 demo:2 E:4 elevensection:2 example:2 F:4 false:2 from:2 G:4 H:6 HashSet:3 holding:1 I:3 import:4 in:4 J:3 java:4 K:3 L:3 M:4 main:1 N:3 new:2 Output:1 package:1 Print:1 print:8 public:2 remove:1 removeAll:1 removed:2 Set:3 set1:23 set2:11 SetOperations:2 split:3 static:2 String:5 to:2 true:2 util:3 void:1 X:4 Y:4 Z:4
*///:~
posted @ 2022-08-24 19:20  loadL  阅读(20)  评论(0)    收藏  举报