Java program to print duplicates from a list of integers


In order to find duplicates we can utilize the property of Set in Java that in Java duplicates are not allowed when going to be added in a Set.Add method of set returns true for the adding value which is not added previously to it while it would return false in case the adding value is already present in the Set.

For our agenda we would iterate out list or collection of integer and try to add each integer in a set of type integer.Now if integer gets added than this means that it is occurring for first time and not seems to be duplicate while if integer is not get added as Set add method returns false than it implies that it occurring again and is duplicate in the given list or collection.So for these type of integers which are duplicates we would add them in other set which would be our resultant duplicate integers.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class DuplicateIntegers {
   public static void main(String[] args) {
      ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1,2,3,4,45,55,3,32,22,22,55,1));
      HashSet<Integer> hCheckSet = new HashSet<>();
      HashSet<Integer> hTargetSet = new HashSet<>();
      for (Integer integer : arr) {
         if(!hCheckSet.add(integer)) {
            hTargetSet.add(integer);
         }
      }
      System.out.println("Duplicate integers in given list is/are " + hTargetSet);
   }
}

Output

myCSV.csv file created with following text

Duplicate integers in given list is/are [1, 3, 55, 22]

Updated on: 25-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements