How to count the number of occurrences of an element in an array in java

What you will learn here about Java

  • How to count the number of occurrences of an element in an array in java

In java with stream it is very easy to find the occurrences of an element in an array. Here we will try to know how to count the number of occurrences of an element in an array in Java with sample program.

How to count the number of occurrences of an element in an array in java

The sample program for counting occurrences of an element in an array in java is given below.

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ArrayElementCount {
    public static void main(String[] args) {
        String companies[]={"Google","Apple","Microsoft","Google","Apple","Apple","Google","Google"};
        Map<String, Long> count= Arrays.stream(companies).collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
        System.out.println("Companies occurrence: "+count);
    }
}

OUTPUT

Companies occurrence: {Google=4, Apple=3, Microsoft=1}

You may also like...