Java 中使用流的数字出现次数

Occurences of a number using streams in Java

我有一个包含一些重复数字的整数列表。 如何使用流计算该列表中特定数字的出现次数?

  List<Integer> newList = new ArrayList<>();

        newList.add(3);
        newList.add(6);
        newList.add(6);
        newList.add(6);
        newList.add(4);
        newList.add(9);
        newList.add(0);

例如,对于数字 6,我想 return 3.

编辑:我知道如何使用传统的 for 循环来完成它,但我想知道是否有使用流的方法。

您可以使用 groupingBy 如下所示:

Map<Integer, Long> map = newList.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(map);

输出:

{0=1, 3=1, 4=1, 6=3, 9=1}

然后你可以得到单个元素的值:

System.out.println(map.get(6));
newList.stream()
    .filter(x->x==6)
    .count();

将为您提供 6.

的出现次数