
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge Duplicates of a List Using TreeSet in Java
In this article, we will learn to merge duplicate elements from a List in Java by using a TreeSet. This program will take a List of strings containing duplicate values, transfer the elements into a TreeSet, and display the unique, sorted elements. Using a TreeSet is ideal here because it automatically removes duplicates and orders the elements in natural order.
Problem Statement
Write a Java program to remove duplicate elements from a list using a TreeSet. The program should take a list with repeated elements, convert it into a TreeSet to eliminate duplicates, and display the unique, sorted elements.
Input
[A, B, C, D, D, E, F, G, E]
Output
TreeSet = [A, B, C, D, E, F, G]
Steps to merge duplicates of a List with TreeSet
Following are the steps to merge duplicates of a List with TreeSet ?
- Import ArrayList, TreeSet, and List from the java.util package at the start of the program, as these classes are necessary for creating lists and sets.
- We will use ArrayList to create a list named ls and add elements to it, including duplicate values like "D" and "E".
- Create a TreeSet named set. TreeSet automatically sorts the elements and removes duplicates.
- Use the addAll() method from the TreeSet class to add all elements from ls to set. This method ensures that duplicates are removed, and the elements are stored in sorted order.
- Print the TreeSet, displaying the unique and sorted elements.
Java program to merge duplicates of a List with TreeSet
Below is the Java program to merge duplicates of a List with TreeSet ?
import java.util.ArrayList; import java.util.TreeSet; import java.util.List; public class Demo { public static void main(String[] args) { List<String>ls = new ArrayList<String>(); ls.add("A"); ls.add("B"); ls.add("C"); ls.add("D"); ls.add("D"); ls.add("E"); ls.add("F"); ls.add("G"); ls.add("E"); TreeSet<String>set = new TreeSet<String>(); set.addAll(ls); System.out.println("TreeSet = "+set); } }
Output
TreeSet = [A, B, C, D, E, F, G]
Code explanation
The above program begins by importing ArrayList, TreeSet, and List from java.util. We create an ArrayList (ls) with some duplicate elements, then initialize a TreeSet (set). Since TreeSet removes duplicates and sorts elements, adding ls to set with addAll() filters out duplicates and sorts the list. Finally, we will display the unique, sorted elements in set. This approach efficiently merges and sorts duplicates from the list.