English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To find duplicates, we can take advantage of the properties of Set in Java, where it is not allowed to add duplicate items to a Set in Java. The Set add method returns true for adding a value that has not been added before. If the value already exists in the Set, it returns false.
For our agenda, we will traverse the list or collection of integers and try to add each integer to a collection of integer type. If an integer is added now, it means it is the first occurrence, and if the integer is not added, because the Set add method returns false, it means it has occurred again and is a duplicate in the given list or collection. Therefore, for these duplicate integer types, we will add them to another set, which will be the duplicates we get.
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 Result
The myCSV.csv file is created using the following text
Duplicate integers in given list is/are [1, 3, 55, 22]