Given an array of integers with duplicates, write a program to print unique elements in the array in sorted order.
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; /** * * @author Lenovo */ import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class JavaApplication1 { /** * @param args the command line arguments */ public static void sortedDistinct(int [] input){ System.out.println("Given Input: " + Arrays.toString(input)); Set<Integer> set = new TreeSet<>(); for (int i = 0; i <input.length ; i++) { set.add(input[i]); } //print the set System.out.println("Sorted Distinct Elements: "); Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } } public static void main(String[] args) { int [] input = {6, 1, 8, 5, 2, 10, 17, 25, 6, 5, 1, 8, 8}; sortedDistinct(input); } } |
Output: