[英]Loop for counting the number of occurrences of a word in an array of words
如何设置一个循环来计算数组(不是 ArrayLists)中单词的出现次数。 这是我设置的循环,但将其打印出来只会给我一个从 0 到单词数组大小的数字数组。 我还想将每个单词的计数值存储到一个数组中
int[] wordCountList = new int[arrayCount]; //arrayCount is just the size of the array of words
int counter = 0;
for(int p = 0; p < words.length; p++)
{
String currentItem = words[p]; //words is the array of words
if(words[p].equals(currentItem))
{
wordCountList[p] = counter++;
}
}
另外,如果我先按字母顺序对数组进行排序,然后计算每个单词的出现次数,会不会更好?
使用 Java 8 流 API
String[] words = {"banana", "lemon", "banana", "apple"};
Map<String, Long> wordsCount = Stream.of(words).collect(
Collectors.groupingBy(Function.identity(), Collectors.counting()));
Function.identity()
具有“项目本身”的含义。
解决此问题的典型方法是使用HashMap
将出现的事件存储为键值对
Map<String, Integer> map = new HashMap<>();
for(String word: words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
System.out.println(map)
现在map
会将每个单词映射到它出现的次数,假设您有以下示例
String[] words = {"banana", "lemon", "banana", "apple"};
那么地图将包含
banana ==> 2
lemon => 1
apple => 1
您的代码大部分都很好,唯一的问题是,您没有定义要查找的单词。
int[] wordCountList = new int[arrayCount]; //arrayCount is just the size of the array of words
for(int p = 0; p < words.length; p++){
//int counter = 0;
for(String needle : words){
//String currentItem = words[p]; //words is the array of words
if(words[p].equals(needle)){
wordCountList[p]++;
}
}
}
对于它的价值,可以更快地数词吗? 是的,但只能通过排序(例如。bucketsort aka。哈希)。
@mehdi:有没有办法让你的解决方案区分大小写
例如,如果我们将一根香蕉换成香蕉,答案将是 difference {"Banana", "lemon", "banana", "apple"} ===> {banana=1, apple=1, lemon=1, Banana= 1} 而不是 {Banana=2, apple=1, lemon=1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.