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.

import java.util.*;
public class NoDuplicates
  public static void main(String args[])
    Vector vect1 = new Vector();
    vect1.add("Rose");     vect1.add("Jasmine");        // observe, Rose and Jasmine are repeated
    vect1.add("Jasmine");  vect1.add("Rose");

    HashSet hs1 = new HashSet(vect1);   // HashSet keeps only unique elements by default
                                                        // if you would like Vector back
    Vector vect2 = new Vector(hs1);

    System.out.println("Vector with duplicates: " + vect1);
    System.out.println("Vector without duplicates: " + vect2);
                                                        // if you would like the Vector elements in sorted order

    TreeSet s1 = new TreeSet(vect1);    // TreeSet sorts the elements by default
    // System.out.println("SortedSet elements: " + s1); // you can print like this also

    // if you would like Vector back
    Vector vect3 = new Vector(s1);
    System.out.println("Vector without duplicates and in sorted order: " + vect3);

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 Comment

Your email address will not be published.