How to Convert a TreeSet to ArrayList

In Order to Convert TreeSet to AraryList in Java , We have couple of ways . We Knew that ArrayList In Java is a ordered collection and allow duplicate element . But TreeSet in Java is avoids duplicates. We Can convert Set to List in java using below method

1. Using ArrayList Constructor –

Firstly , We will  create  a set and pass as a argument in ArrayList constructor. If you didn’t know much about ArrayList constructor i will recommenced to you first read this How to create ArrayList In Java .

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetToList {

public static void main(String[] args) {

Set<String> ts = new TreeSet<String>();
ts.add("mumbai");
ts.add("delhi");
ts.add("kolkata");
ts.add("chandigarh");
ts.add("dehradun");

// print treeset
System.out.println(" ts ="+ts);

List<String> list = new ArrayList<String>(ts);

for (String str : list) {
System.out.println(" List Element is = "+str);
}

}

}

Output:

ts =[chandigarh, dehradun, delhi, kolkata, mumbai]

List Element is = chandigarh

List Element is = dehradun

List Element is = delhi

List Element is = kolkata

List Element is = mumbai

2. Using AddAll() Method

ArrayList Provides AddAll() Method Which can append element in the collection .With the help of addAll() method we can convert set to arraylist/linkedlist/list. For this we will create a hashset aadd element in to it. Now we create a list and add element of set in to  list with the help of addAll() method as.

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

public class ArrayToListByAllAdd {

	public static void main(String[] args) {
	
		Set<String> ts = new TreeSet<String>();
		ts.add("mumbai");
		ts.add("delhi");
		ts.add("kolkata");
		ts.add("chandigarh");
		ts.add("dehradun");
		
		ArrayList<String> arrayList = new ArrayList<String>();

		arrayList.addAll(ts);
	
		System.out.println("list is ="+ arrayList);

	}
	
}

Output :

list is =[chandigarh, dehradun, delhi, kolkata, mumbai]

We can convert Set to LinkedList Using these Ways.

Reference :

A Guide To TreeSet

Java Docs – TreeSet

 

Leave a Reply

Your email address will not be published. Required fields are marked *

59 − = 55