給定一長串以空白分隔的單字字串,需求為:
1. 依字母順序排序
2. 統計每個單字出現次數
3. 去除重複並輸出「單字:次數」格式
String.split(" ") 切割成陣列Arrays.sort() 原地排序TreeSet 自動去重且保持排序順序package action;
import java.util.Arrays;
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
String strs = "ZZZ BBB AAA OOO ZZZ AAA ZZZ BBB AAA ZZZ AAA VVV OOO CCC DDD CCC CCC KKK BBB AAA ZZZ AAA CCC KKK";
String[] words = strs.split(" ");
TreeSet<String> resultSet = new TreeSet<>();
Arrays.sort(words); // 先排序
for (int i = 0; i < words.length; i++) {
int count = 0;
for (int j = 0; j < words.length; j++) {
if (words[i].equals(words[j])) count++;
}
resultSet.add(words[i] + ":" + count);
}
for (String s : resultSet) {
System.out.println(s);
}
}
}
AAA:7
BBB:5
CCC:5
DDD:1
KKK:2
OOO:2
VVV:1
ZZZ:7
Map<String, Integer> map = new HashMap<>(),單次遍歷 O(n) 完成計數。Arrays.stream(words)
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(e -> System.out.println(e.getKey() + ":" + e.getValue()));
TreeSet 依據 compareTo 判斷相等,若物件未正確實作 Comparable 可能導致去重失效。