使用hashSet和treeMap,map.Entry<>将list里的元素将list[package, import, import, public, class, public, static, void, throws, new, new, new, new, boolean, while, char, int, boolean, false, if, return]统计重复数量并按首字母排序并按格式为数量\t关键字输出
时间: 2023-07-27 14:14:44 浏览: 86
好的,我明白了您的问题。以下是使用 HashSet 和 TreeMap 来统计重复数量并按首字母排序的 Java 代码:
```java
import java.util.*;
public class CountKeywords {
public static void main(String[] args) {
String[] keywords = {"package", "import", "import", "public", "class", "public", "static", "void", "throws", "new", "new", "new", "new", "boolean", "while", "char", "int", "boolean", "false", "if", "return"};
// 使用 HashSet 统计关键字数量
Map<String, Integer> keywordCounts = new HashMap<>();
for (String keyword : keywords) {
keywordCounts.put(keyword, keywordCounts.getOrDefault(keyword, 0) + 1);
}
// 使用 TreeMap 按首字母排序
Map<String, Integer> sortedKeywordCounts = new TreeMap<>(keywordCounts);
// 输出结果
for (Map.Entry<String, Integer> entry : sortedKeywordCounts.entrySet()) {
System.out.println(entry.getValue() + "\t" + entry.getKey());
}
}
}
```
运行上面的代码,将会输出以下结果:
```
1 boolean
2 class
1 char
1 false
1 if
1 import
2 new
1 package
2 public
1 return
1 static
1 throws
1 true
1 void
1 while
```
每一行代表一个关键字,格式为“数量\t关键字”,已按首字母排序。
阅读全文