Tuesday, 29 May 2018

Java Program to find all duplicate elements in List



Sample Program:-


 import java.util.ArrayList;  
 import java.util.List;  
 public class SampleProgram {  
      public static void main(String[] args) {  
           List<Integer> list = new ArrayList<Integer>();  
           list.add(1);  
           list.add(2);  
           list.add(5);  
           list.add(3);  
           list.add(3);  
           list.add(1);  
           list.add(7);  
           System.out.println("Original list: " + list);  
           List<Integer> newList = new ArrayList<Integer>();  
           System.out.print("Duplicate numbers in list are: ");  
           for (int i : list) {  
                if (newList.contains(i))  
                     System.out.print(i + " ");  
                else  
                     newList.add(i);  
           }  
      }  
 }  

Output:-


 Original list: [1, 2, 5, 3, 3, 1, 7]  
 Duplicate numbers in list are: 3 1   

Enjoy Coding.

No comments:

Post a Comment