如何从词频Map中筛选频率为偶数的单词并加入List?
Hey there! I see where you're stuck—your second loop is only iterating over the count values, not the corresponding words (keys) from the map. That's why you can't add the right words to your result list. Let's fix this up step by step.
The Issue in Your Code
Your current second loop loops through wordsWithCount.values(), which only gives you the integer counts. You need to access both the word (key) and its count (value) to check if the count is even, then add the word to your result list.
Modified Working Code
Here's the updated version of your method, with fixes and a small optimization to the counting logic:
public static List<String> onlyEvenWordsList(List<String> words) { Map<String, Integer> wordsWithCount = new HashMap<>(); List<String> onlyEvenWords = new ArrayList<>(); // Optimized counting using getOrDefault to simplify null checks for (String word : words) { wordsWithCount.put(word, wordsWithCount.getOrDefault(word, 0) + 1); } // Iterate over map entries to access both word and count for (Map.Entry<String, Integer> entry : wordsWithCount.entrySet()) { String word = entry.getKey(); int count = entry.getValue(); if (count % 2 == 0) { onlyEvenWords.add(word); } } return onlyEvenWords; }
Key Changes Explained
- Simplified Counting: Used
Map.getOrDefault()to eliminate the null check for the count value—this method returns 0 if the word isn't in the map yet, then we increment it by 1. - Iterated Over Entries: Instead of looping through just values, we loop through
entrySet(), which gives usMap.Entryobjects containing both the word (key) and its count (value). This lets us check the count and add the matching word to the result list directly.
Optional: Stream API Alternative (For Cleaner Code)
If you're using Java 8+, you can simplify the entire method using streams, which makes it more concise:
public static List<String> onlyEvenWordsList(List<String> words) { return words.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(entry -> entry.getValue() % 2 == 0) .map(Map.Entry::getKey) .collect(Collectors.toList()); }
This does the same thing—groups words by their value, counts occurrences, filters for even counts, extracts the words, and collects them into a list.
内容的提问来源于stack exchange,提问作者TheWhiteFoxter

