Hi All,

Greetings for today!

Today we will see how to write a program with Java 8 to find the number of occurrences of the elements in a List, We'll also look at how to find all duplicate elements in an ArrayList, so let's get started.

First, declare and initialize a list of integers, along with a Map that will be used to store the number of occurrences of elements, as shown below.
  List integerList=List.of(20,51,14,29,44,20);
  Map integerMap=new HashMap();  
Note - In the above Map, the key will be an element of the list and the value will be the number of occurrences of that element.

Now iterate over each element of the list and use the containsKey method of Map. So the basic logic here is that if the map doesn't contain an element of the list, insert that element into the map with value 1. 

If the map contains this element, update the number of occurrences of this element to the existing number of occurrences, with a value of +1 each time.
package com.demo.programs;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CountDuplicateInList {

    public static void main(String[] args) {
        List integerList=List.of(20,51,14,29,44,20);
        Map integerMap=new HashMap<>();

        integerList.stream().forEach(integer -> {
            if(integerMap.containsKey(integer)){
                integerMap.put(integer,integerMap.get(integer)+1);
            }else{
                integerMap.put(integer,1);
            }
        });

        integerMap.forEach((integer, integer2) -> {
            System.out.println("Inter "+integer + " is coming "
                    +integer2 + "times");

            if(integerMap.get(integer)>1){
                System.out.println("Duplicate element is "
                        + integer);
            }
        });
    }
}

So after filling out the map, you can check if the number of any element is greater than 1. If so, the element is a duplicate. The above code also outputs the elements along with their number of occurrences.

Feel free to comment if you encounter any issues while implementing the above solutions. we will try to help you.

Thanks
Enjoy your learning!

Other articles you can refer to