计算单词数组中单词出现次数的循环

时间:2019-02-01 19:46:09

标签: java arrays loops sorting count

一个人如何建立一个循环来计算一个单词(不是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++;
        }
    }

此外,如果我先按字母顺序对数组进行排序,然后计算每个单词的出现次数,会更好吗?

3 个答案:

答案 0 :(得分:1)

使用Java 8 Stream API

String[] words = {"banana", "lemon", "banana", "apple"};
Map<String, Long> wordsCount = Stream.of(words).collect(
    Collectors.groupingBy(Function.identity(), Collectors.counting()));

Function.identity()的含义是“项目本身”。

答案 1 :(得分:0)

解决此问题的一种典型方法是使用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

答案 2 :(得分:0)

你的代码主要是罚款,唯一的问题是,你不定义你正在寻找的话。

 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.hash)来实现。

相关问题