Tuesday 21 January 2014

Finding duplicates from List

Finding the duplicates from List: The below program is for finding the duplicates from the list and return the duplicate values.finding the duplicates from the list this will be useful for any interviews as well as best programming practice to the beginners in developement. please make sure that it is one way i have shown to you. but as a programmer we can write multiple logics for the same.if you have such type of logics please comment it below then everyone can come to know the different ways to find out the same solution.

//Finding the duplicates from list

import java.util.*;

public class FindOutRepeatedNum {

public static void main(String[] args) {
List<Integer> listContainingDuplicates = new ArrayList<Integer>();

for (int i = 0; i < 20; i++) {
listContainingDuplicates.add(i);
}
//addding duplicates
listContainingDuplicates.add(1);
listContainingDuplicates.add(3);
listContainingDuplicates.add(5);

FindOutRepeatedNum forn = new FindOutRepeatedNum();
Set<Integer> set = forn.findDuplicates(listContainingDuplicates);

for (Integer intval : set) {
System.out.println(intval);
}
}

public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)

 final Set<Integer> setToReturn = new HashSet<Integer>(); 
 final Set<Integer> set1 = new HashSet<Integer>();

 for (Integer yourInt : listContainingDuplicates)
 {
 //if a set is not going add a repeated value that time we are going to add the repeated value to another set (because set never allowed duplicates)
  if (!set1.add(yourInt))
  {
   setToReturn.add(yourInt);//adding duplicate value to set
  }
 }
 return setToReturn;
}

}



OUTPUT:
1
3
5