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

Convert String to Date Using java.util.Calendar

The java.util.Calendar class also encapsulates a date. The Calendar class has some more features than the java.util.Date class. It provides the ability to extract...

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...

Convert String to java.time.LocalDate without Formatter

The LocalDate class has a parse method. You can use this to convert a String to a LocalDate. So, this code simply invokes the...

Â

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...

Does VBScript Supports all COM Objects ?

Well the answer in one line is - No VBScript does not supports all COM Objects or Servers! VBScript works with only a subset of ‘Objects’...

How To Install Pacman For Git on Windows

The 'Git for Windows' by default does not come with MSYS2 package manager called 'Pacman' and hence it is a limited version or subset...

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