【问题标题】:Number of appearence of each word of hashtable in an arrayhashtable的每个单词在数组中出现的次数
【发布时间】:2021-03-20 04:49:12
【问题描述】:

我正在尝试 sysout 数组中哈希表值的出现次数

我正在使用

    int count;
    int len = array.length;
    for (Map.Entry<String, String> entry : keyword.hashtable().entrySet()) {
        count = 1;
        for (int i = 0; i < len; i++) {
            t = array[i];
            if (entry.getValue().equals(t)) {
                System.out.println(" " + entry.getValue() + ": " + count);
                count++;
            }
        }
    }

但是输出看起来是这样的

 only: 1
 only: 2
 was: 1
 was: 2
 was: 3
 was: 4
 it: 1
 in: 1
 in: 2
 in: 3
 the: 1
 the: 2
 the: 3
 the: 4
 the: 5
 the: 6
 the: 7

我怎样才能用出现次数只用一次这个词?

这样

 only: 2
 was: 4
 in: 3
 the: 7

【问题讨论】:

  • 它正在为您计算的每一项打印,因为您告诉它为您计算的每一项打印。仅在执行计数的循环完成后打印计数。

标签: java arrays hashtable


【解决方案1】:

如果您正确创建了频率图,则在迭代地图时不需要内部循环。

演示:

import java.util.HashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) {
        String[] arr = { "the", "in", "the", "only", "the", "was", "the", "it", "the", "was", "in", "only", "the",
                "was", "the", "was", "in" };

        // Create the frequency map
        Map<String, Integer> map = new HashMap<>();
        for (String s : arr) {
            map.merge(s, 1, Integer::sum);
        }

        // Display
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

输出:

the: 7
in: 3
was: 4
only: 2
it: 1

【讨论】:

    【解决方案2】:

    您可以使用 java 8 提供的流。

    public static void main(String[] args) {
        List<String> arr = Arrays.asList("the", "in", "the", "only", "the", "was", "the", "it", "the", "was", "in", "only", "the",
                "was", "the", "was", "in");
        Map<String, Long> numOccurrences = arr.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(numOccurrences);
    }
    

    输出:

    {the=7, in=3, was=4, only=2, it=1}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多