Java Program to merge duplicates of a List with TreeSet

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 24-Apr-2019 15:03:41
Advertisements