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

Remove Duplicates from List Using Set.addAll

The Set interface has a method called addAll. This accepts a 'Collection' as the parameter. So if you invoke this method by passing the...

Create Basic Hibernate Program

Hibernate is an ORM framework that helps in accessing database tables from Java code. It is an object-oriented way of accessing database tables and...

Concatenate Strings Using Plus Operator

In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

Â

MORE IN THIS CATEGORY

Java Tutorial #5 – Loop Statements

Iteration statements are used to repeat a particular block of code until a certain condition is true. In this article, we will be taking...

How To Sort List in Java

Introduction A List is an interface in the Java collection framework. It can be used to store objects. Programmers often encounter scenarios where they need...

Maven Build Life Cycles, Phases and Goals

Maven’s Sequential Execution In Maven, you have the option of executing a build phase or build goal. But unlike build goals, which can be called...

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