How to Find duplicate numbers in given list in Java

For this program we are going to use HashSet as Set does not allow duplicate elements.

We will be using two HashSets . As he list is traversed ,all the elements will be started storing in the first hash set and if any element is traversed again the first hash set will not allow that element and that element will be stored in the second hash set and at last we ll print the second Hash set .

package com.javainhouse;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class findDuplicateElements

public static void main(String[] args) {
List<String> list = new LinkedList<String>();
for (int i = 0; i < 10; i++) {
for (int i = 2; i < 7; i++) {
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
for (String element : list) {
if (!set1.add(element)) {
System.out.println("Original List : " + list);
System.out.println("Duplicate elements from list : " + setToReturn);

OutPut :

Duplicate Elements in List Program

Post a Comment