How to Create a TreeSet with a List in Java


In this example we will show the method to create a TreeSet with a list. The TreeSet class has a constructor that accepts a Collection object, and you can use this constructor to specify a Collection object to create the TreeSet. As shown below.

Source Code

package com.beginner.examples;

import java.util.ArrayList;
import java.util.TreeSet;

public class CreateTreeSetWithList {

	public static void main(String[] args) {
		
		ArrayList nums = new ArrayList();
		
		nums.add(2);
		nums.add(3);
		nums.add(1);
		nums.add(0);
		
		//Specify a list collection to create the TreeSet 
		TreeSet numSet = new TreeSet(nums);
		
		for(Integer i : numSet) {
			
			System.out.print(i+" ");
			
		}
		
	}
	
}

Output:

0 1 2 3 

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments