How to print the duplicate elements of an array

There are multiple way to print the duplicate elements of an array.

From for loop method :-

In this program, we take two for loops. The first for loop will select an element and the second for loop will iteration through the array by comparing the selected element with other elements. If a[i]==a[j] return true then match is found, print the duplicate element.

From Set method :-

  • Create the object of HashSet.
  • Through for loop will iteration the array elements.
  • Inside if condition use contains method.this method returns true if the element is present in the set else return False.

Syntax :         boolean contains(Object element)

				
					import java.util.HashSet;
import java.util.Set;

public class DuplicateArrayElements {
	public static void main(String[] args) {
		int a[] = { 1, 2, 3, 1, 2, 4, 6 };
		System.out.println("from for loop method duplicate element are :- ");
		for (int i = 0; i < a.length; i++) {
			for (int j = i + 1; j < a.length; j++) {
				if (a[i] == a[j]) {
					System.out.println(a[i]);
				}
			}
		}
		Set<Integer> ht = new HashSet<Integer>();
		System.out.println("from HashSet method duplicate element are :- ");
		for (int i = 0; i < a.length; i++) {
			if (ht.contains(a[i])) {
				System.out.println(a[i]);
			} else {
				ht.add(a[i]);
			}
		}
	}
}

				
			

Output :-
from for loop method duplicate element are :-
1
2
from HashSet method duplicate element are :-
1
2