How to print the duplicate elements of an array in Java

4 Answers

0 votes
public class MyClass {
    public static void printDuplicates(int[] arr) {
        for (int i = 0; i < arr.length; i++) {  
            for (int j = i + 1; j < arr.length; j++) {  
                if (arr[i] == arr[j]) {
                    System.out.println(arr[j]);
                }
            }  
        }
    }
   
    public static void main(String args[]) {
        int[] arr = { 3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9 };
   
        printDuplicates(arr);
    }  
}
   
   
/*
run:
   
3
9
9
1
9
   
*/

 



answered May 1, 2020 by avibootz
edited May 22 by avibootz
0 votes
import java.util.Set; 
import java.util.HashSet; 
  
public class MyClass {
    public static void printDuplicates(int[] array) {
        Set<Integer> dup = new HashSet<Integer>();
        for (int n : array) {
            if (!dup.add(n)) {
                System.out.println(n);
            }
        }
    }
  
    public static void main(String args[]) {
        int[] arr = { 3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9 };
  
        printDuplicates(arr);
    }  
}
  
  
/*
run:
  
1
9
3
9
  
*/

 



answered May 1, 2020 by avibootz
edited May 22 by avibootz
0 votes
import java.util.Set; 
import java.util.HashSet; 

public class MyClass {
    public static <T> void printDuplicates(T[] array) {
        Set<T> dup = new HashSet<T>();
        for (T n : array) {
            if (!dup.add(n)) {
                System.out.println(n);
            }
        }
    }
   
    public static void main(String args[]) {
        Integer[] arr = { 3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9 };
   
        printDuplicates(arr);
    }  
}

   
   
/*
run:
   
1
9
3
9
   
*/

 



answered May 1, 2020 by avibootz
edited May 22 by avibootz
0 votes
import java.util.Map; 
import java.util.HashMap; 

public class MyClass {
    public static void printDuplicates(int[] arr) {
        Map<Integer, Integer> hm = new HashMap<>();
  
        for (int i = 0; i < arr.length; i++) {
            if (hm.containsKey(arr[i])) {
                hm.put(arr[i], hm.get(arr[i]) + 1);
            } else {
               hm.put(arr[i], 1);
            }
        }
        for (Integer key: hm.keySet()) {
            if (hm.get(key) > 1) {
                System.out.println(key); 
            }
        } 
    }
   
    public static void main(String args[]) {
        int[] arr = { 3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9 };
   
        printDuplicates(arr);
    }  
}

   
   
/*
run:
   
1
3
9
   
*/

 



answered May 2, 2020 by avibootz
edited May 22 by avibootz
...