Java Program to merge duplicates of a List with TreeSet


Let’s say the following is a List. In this, we have duplicates elements as well −

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");

Now, create a TreeSet and merge the duplicates of the List −

TreeSet<String>set = new TreeSet<String>();
set.addAll(ls);

Example

 Live Demo

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]

Updated on: 30-Jul-2019

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements