Java Program to Remove Duplicate Entries from an Array using TreeSet
Features of TreeSet is the primary concern it is widely used in remove duplicates in the data structure as follows:
- TreeSet implements the SortedSet interface. So, duplicate values are not allowed and will be leftovers.
- Objects in a TreeSet are stored in a sorted and ascending order.
- TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
- If we are depending on the default natural sorting order, the objects that are being inserted into the tree should be homogeneous and comparable. TreeSet does not allow the inserting of Heterogeneous objects. It will throw a classCastException at Runtime if we try to add heterogeneous objects.
Approach: add() method of Set
In Java, here it is used in context to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.
boolean add(E element) Where, E is the type of element maintained by this Set collection.
- Create an object of TreeSet.
- Add array elements to the TreeSet using the add() method.
- Print and display elements in an array that are duplicated using add(element) method.
- Print and display elements in an array after removing duplicates from it.
- Getting size of TreeSet using size() method.
- Converting above TreeSet to arrays using toArray() method for conversion.
- Iterating over array elements.
- Print and display the above string array after removing duplicate entries from it.
In the below example we are Addition for every element of the Array to the TreeSet later on checking for duplicates. Finally, putting all the elements of TreeSet in Array and put “null” for all leftover spaces in Array, and printing the elements of the array.
Initial String Array(Containing Duplicates) : [Hello, hi, Wow, cute, thanks, hi, Aww, cute, baby, beloved, Aww]Duplicate Data entered : hi Duplicate Data entered : cute Duplicate Data entered : Aww TreeSet(After Removing Duplicates) : [Aww, Hello, Wow, baby, beloved, cute, hi, thanks] Final String Array is : [Aww, Hello, Wow, baby, beloved, cute, hi, thanks, null, null, null]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.