Given an array with multiple duplicate elements print all the duplicate elements once from it in sorted order.
For Example:
Input1: 9
Input2: {3,5,2,4,2,3,9,9,9}
Output: 2,3,9
Explanation:
The explanation is pretty straight forward as in the array:
2 occurs 2 times
3 occurs 2 times and
9 occurs 3 times
So these elements have duplicated records in the array and should be printed.
CODE:
package arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.TreeSet;
public class PrintAllDuplicateElementsInSortedOrder
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length of Array");
int n = sc.nextInt();
int ar[] = new int[n];
System.out.println("Enter the array Elements");
for (int i = 0; i < n; i++)
{
ar[i] = sc.nextInt();
}
print(ar);
}
public static void print(int ar[])
{
HashSet<Integer> hs= new HashSet<>();
TreeSet<Integer> ts= new TreeSet<>();
for(int i:ar)
{
boolean check=hs.add(i);
if(!check)
{
ts.add(i);
}
}
//printing the required elements
for(int i:ts)
{
System.out.print(i+" ");
}
}
}
OUTPUT:
Enter the length of Array
9
Enter the array Elements
3 5 2 4 2 3 9 9 9
2 3 9