英文:
How to get even values from map and then adding value key to list?
问题
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);
}
for(Integer value: wordsWithCount.values()){
if(value % 2 == 0){
onlyEvenWords.add(value); // Add the word to the onlyEvenWords list
}
}
return onlyEvenWords;
}
英文:
Alright, so my problem here right now is that I can get all the words from a list, find the occurrence and then add key and value pairs to map, but since I need to return a list of words which frequency is even, I get stuck. Any help?
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);
}
for(Integer value: wordsWithCount.values()){
if(value % 2 == 0){
....
}
}
return onlyEvenWords;
}
答案1
得分: 0
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);
}
for (Map.Entry<String, Integer> entry : wordsWithCount.entrySet()) {
if (entry.getValue() % 2 == 0) {
onlyEvenWords.add(entry.getKey());
}
}
return onlyEvenWords;
}
// 在主函数中打印列表
System.out.println(Arrays.toString(onlyEvenWordsList(words).toArray()));
英文:
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);
}
for(Map.Entry<String, Integer> entry: wordsWithCount.entrySet()){
if(entry.getValue()%2==0){
onlyEvenWords.add(entry.getKey());
}
}
return onlyEvenWords;
}
And to print the list in main
System.out.println(Arrays.toString( onlyEvenWordsList(words).toArray()));
专注分享java语言的经验与见解,让所有开发者获益!
评论