How to count the number of occurrences of an element in a list in Java

What you will learn here about java

  • How to count the number of occurrences of an element in a list in Java

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

How to count the number of occurrences of an element in a list in Java

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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ElementCount {

    public static void main(String[] args) {

        List<String> company = new ArrayList<>();

        company.add("Apple");
        company.add("Google");
        company.add("Nokia");
        company.add("HTC");
        company.add("HTC");
        company.add("Google");
        company.add("Google");
        company.add("Google");
        company.add("Apple");
        company.add("Apple");
        company.add("Apple");

        Map<String, Long> count = company.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println("Element occurrence : "+count);

    }

}

OUTPUT

Element occurrence : {Google=4, Apple=4, HTC=2, Nokia=1}

You may also like...