Remove Duplicates from List Using HashSet

The Set is also an interface in the ‘Java Collection‘ framework. Unlike a List, a Set does not allow duplicates. Hence you can use a Set to eliminate the duplicates in a List. There are several ways in which you can use a Set to eliminate duplicates as demonstrated below:

The most commonly used implementation of Set is HashSet. HashSet has a constructor which accepts a Collection as a parameter. So basically, if you create a new HashSet using this constructor and pass in the List as input, this will eliminate the duplicates. The following code demonstrates this:

Here, a new HashSet is created by passing the List as input. So this will automatically create a Set with the elements in the List and eliminate the duplicates. So this code prints the same output as before:

35 20 5 40 25 10 15

The problem with HashSet is that it does not maintain the order of elements. So you can see that the order of elements in the output is different from that in the input list.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Concatenate Strings Using String.join()

Java 8 has added a static join method to the String class. This concatenates Strings using a delimiter. Performance wise, it is similar to...

Remove Duplicates from List Using Stream

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() method has been...

Remove Duplicates from List Using For-Loop

The simplest way to remove duplicates from a 'List' is to use a for-loop. The following code snippet demonstrates this method. First, the code creates...

Â

MORE IN THIS CATEGORY

How To Setup Automatic SSH-Agent for GitBash

Using below procedure, you shall be able to setup SSH-Agent to run automatically whenever GitBash is launched on Windows. The ssh-agent process will continue...

Convert String to Date Using SimpleDateFormat Class

Sometimes, you may need to convert a String to a java.util.Date object. For this, you need to use the SimpleDateFormat class. You need to...

How To Convert List To Array in Java

A common scenario faced by programmers is to convert a Java List to an Array. A 'List' is part of the Collection Framework and...

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

SIMILAR ON CODEX

- Advertisement -spot_img