这个练习的重点是计算列表中单词的出现次数,并将列表中出现的第二次、第四次、第六次等的单词添加到结果列表中。到目前为止,我只能计算每个单词的出现次数,并且只能将计数为偶数的单词添加到结果列表中。例如,如果我遍历一个列表,第一次获得“a”count = 1,第二次获得“a”count = 2 并将“a”添加到列表中,第三次获得“a”,count = 3 和第四次"a" count = 4 并将 "a" 添加到列表中,结果将是 ["a", "a"]
public static List<String> onlyEvenWordsList(List<String> words) {
Map<String, Integer> wordsWithCount = new HashMap<>();
List<String> onlyEvenWords = new ArrayList<>();
for (String word : words) {
Integer count = wordsWithCount.get(word);
if (count == null) {
count = 0;
}
wordsWithCount.put(word, count + 1);
//System.out.println(wordsWithCount);
}
for(Map.Entry<String, Integer> entry: wordsWithCount.entrySet()) {
if(entry.getValue() % 2 == 0){
onlyEvenWords.add(entry.getKey());
}
}
return onlyEvenWords;
}
因此,例如,给定的输入和所需的输出:
System.out.println(onlyEvenWordsList(Arrays.asList("eggs", "bacon", "SPAM", "ham", "SPAM", "SPAM"))); // [SPAM]
System.out.println(onlyEvenWordsList(Arrays.asList("a", "a", "b", "b", "c", "a", "c", "a"))); // [a, b, c, a]
System.out.println(onlyEvenWordsList(Arrays.asList("a", "a", "a"))); // [a]