java—数组中哈希表每个字的出现次数

anhgbhbe  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(363)

我试图计算出数组中哈希表值的出现次数
我正在使用

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
r8uurelv

r8uurelv1#

您可以使用Java8提供的流。

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}
zzzyeukh

zzzyeukh2#

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

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

相关问题