Remove Duplicate Elements from Vector in Java Example

This example shows how to remove duplicate elements from Vector in Java. This example also shows how to remove duplicate elements using LinkedHashSet class and Java 8 Stream.

How to remove duplicate elements from Vector in Java?

There are a couple of ways using which we can remove duplicate elements from Vector in Java as given below.

1. Using the LinkedHashSet class

The Set in Java is a data structure does not allow duplicate elements. When we convert a vector object to such a Set object, only unique elements will be added to it. We can then clear the Vector object and add all elements of the Set back to the vector using the addAll method.

Output

Why convert the vector to LinkedHashSet and not HashSet? Well, the HashSet class does not guarantee the order of the elements. The order of the elements returned by the iterator of the HashSet may not stay constant over time. If you do not want to maintain the insertion order of the elements, you may use the HashSet class as well.

On the other hand, the LinkedHashSet class maintains a doubly-linked list running through its elements and returns the elements in the same order they were inserted into it. That is the reason I choose the LinkedHashSet over HashSet.

2. Using the Java 8 Stream

If you are using Java version 8 or later, you can also use the Java 8 stream to remove duplicate elements from Vector as given below.

Output

This example is a part of the Java Vector Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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