- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove duplicate elements in Java with HashSet
Set implementations in Java has only unique elements. Therefore, it can be used to remove duplicate elements.
Let us declare a list and add elements −
List < Integer > list1 = new ArrayList < Integer > (); list1.add(100); list1.add(200); list1.add(300); list1.add(400); list1.add(400); list1.add(500); list1.add(600); list1.add(600); list1.add(700); list1.add(400); list1.add(500);
Now, use the HashSet implementation and convert the list to HashSet to remove duplicates −
HashSet<Integer>set = new HashSet<Integer>(list1); List<Integer>list2 = new ArrayList<Integer>(set);
Above, the list2 will now have only unique elements.
Example
import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class Demo { public static void main(String[] argv) { List<Integer>list1 = new ArrayList<Integer>(); list1.add(100); list1.add(200); list1.add(300); list1.add(400); list1.add(400); list1.add(500); list1.add(600); list1.add(600); list1.add(700); list1.add(400); list1.add(500); HashSet<Integer>set = new HashSet<Integer>(list1); List<Integer>list2 = new ArrayList<Integer>(set); System.out.println("List after removing duplicate elements:"); for (Object ob: list2) System.out.println(ob); } }
Output
List after removing duplicate elements: 400 100 500 200 600 300 700
- Related Articles
- Remove all elements from a HashSet in Java
- Java Program to Remove duplicate elements from ArrayList
- How to remove duplicate elements of an array in java?
- Remove all elements from a HashSet in C#
- Remove specified element from HashSet in Java
- Remove elements from a HashSet with conditions defined by the predicate in C#
- Add elements to HashSet in Java
- Python – Remove Columns of Duplicate Elements
- Remove single element from a HashSet in Java
- Iterate through elements of HashSet in Java
- Remove all elements in a collection from a HashSet in C#
- Iterate over the elements of HashSet in Java
- Remove duplicate element in a Java array.
- How to remove duplicate elements from an array in JavaScript?
- Remove duplicate items from an ArrayList in Java

Advertisements