Find all duplicate numbers in list in java


In this core java programming tutorial we will write a program to Find all duplicate numbers in list in java.

Q. Find all duplicate numbers in list in java.

Example:
list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 10]
Duplicate numbers in list are: 5 10.






Full Program/SourceCode / Example to Find all duplicate numbers in list in java>
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
import java.util.ArrayList;
import java.util.List;
public class FindDuplicatNumberInListExample {
   public static void main(String[] args) {
          List<Integer> list = new ArrayList<Integer>();     
          for (int i = 1; i <= 10; i++) {
                 list.add(i);
          }
          list.add(5);  //add duplicate number in list.
          list.add(10); //add another duplicate number in list.
          findDuplicateNumbersInList(list);
   }
   /*
   * Method prints duplicate numbers in List and returns list of non-duplicate numbers.
   */
   public static List<Integer> findDuplicateNumbersInList(List<Integer> list) {
          List<Integer> listWithoutDuplicates = new ArrayList<Integer>();
          System.out.println("list is: "+list);
          System.out.print("Duplicate numbers in list are: ");
          for (int i : list) {
                 if (listWithoutDuplicates.contains(i))
                       System.out.print(i+" ");
                 else
                       listWithoutDuplicates.add(i);
          }
          return listWithoutDuplicates;
   }
}
/*OUTPUT
list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 10]
Duplicate numbers in list are: 5 10
*/



So in this core java programming tutorial we wrote a program how to Find all duplicate numbers in list in java.


Previous program                                                                  Next program



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.




RELATED LINKS>

>Pattern/Pyramid generating programs




No comments:

Post a Comment