javaarraylistjava-stream

Occurrences of a number using Java streams


I have an integer list containing some duplicate numbers. How can I count the occurences of a specific number in that list using streams?

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);

For instance, for the number 6 I would like to return 3.

I know how to do it using a traditional for loop, but I was wondering if there's a way using streams.


Solution

  • You can use the groupingBy as shown below:

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

    Output:

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

    Then you can get the value of individual element as:

    System.out.println(map.get(6));