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