We can convert list into treeset by passing list into the TreeSet constructor.
Syntax:
new TreeSet(list);
Example
package com.w3schools; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; public class Test { public static void main(String[] args) { //Create list List<String> list = new ArrayList<String>(); list.add("Jai"); list.add("Mahesh"); list.add("Vishal"); list.add("Hemant"); System.out.println("List elements: "+list); //Convert list into treeset TreeSet<String> treeSet = new TreeSet<String>(list); //Print the TreeSet object. System.out.println("TreeSet elements:"); System.out.println(treeSet); } } |
Output
List elements: [Jai, Mahesh, Vishal, Hemant] TreeSet elements: [Hemant, Jai, Mahesh, Vishal] |