Removing Duplicates Vector

Removing Duplicates Vector


It is a general and interesting code for beginners and this can be achieved in many ways in Java. This code, I would like to keep the code as simple as possible without using any methods and without using any laborious loops of C/C++. Here, I use only constructors but for adding elements to Vector like add().

Concepts used

  1. Vector accepts duplicate elements.
  2. HashSet accepts only unique elements.
  3. TreeSet maintains sorted order.

These concepts are used in the following code.


Removing Duplicates Vector
Output screenshot on Removing Duplicates Vector

Vector elements vect1 are added with duplicate elements of Rose and Jasmine. The Vector object vect1 is passed to the constructor of HashSet hs1. HashSet nature eliminates the dulplicates automatically.

To place the Vector vect1 elements with duplicates in sorted order, the vect1 is passed to the constructor of TreeSet s1. TreeSet eliminates duplicates and also places the elements in sorted order implicitly.

To get the Vector back from HashSet and TreeSet (if required), the Vector objects passed to their constructors as shown in the code.

Leave a Reply

Your email address will not be published. Required fields are marked *