CodesJava

Easy learning with example program codes

how to convert list to treeset in java?


TreeSet

TreeSet extends AbstractSet and implements the NavigableSet interface. It maintains ascending order for its elements i.e. elements will be in sorted form.

We can convert list into treeset by passing list into the TreeSet constructor.

Example

package com.codesjava;
 
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]


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap