In this tutorial we will learn about how to convert java Set to array . We will discuss different example of Set to array conversion using toArray() method , native method (iteration of Set) and java8 .
Convert Set to Array in Java
Let’s discuss different method for how to convert TreeSet to array in java using toArray() method , Using Java8 stream and Native method .
1. Java Set to array Using toArray() Method
Now , We will see how to convert TreeSet to array in java with the help of toArray() method . toArray() method returns an array containing all of the elements in this collection. toArray() method return array of object.
Syntax
public Object[] toArray() {
}
In this approach we will convert Set to array using Set.toArray() method in java method . This is easiest approach . Set.toArray() method returns an array containing all of the elements in this collection. We will create TreeSet and add element into it using add() method . Then we will use set.toArray() method on TreeSet and it returns array of elements of Set.
import java.util.Set;
import java.util.TreeSet;
public class SetToArray {
public static void main(String[] args) {
// Constructs a new, empty set
Set<String> set = new TreeSet<String>();
// add element in it
set.add("java");
set.add("php");
set.add("android");
// display the element Of Set
System.out.println("Set Elements : " + set);
/*
* Returns an array containing all of the elements in this collection
*/
Object[] array = set.toArray();
// print object type array
for (Object object : array) {
System.out.println("Array Element : "+object);
}
}
}
Output:
Set Elements : [android, java, php]
Array Element : android
Array Element : java
Array Element : php
2. Convert Set to array – Iterate Set
In this Approach we will create Set and add some elements into it and create a array of Set size . Then we will iterate Set element and add them to array one by one as per given below java program.
import java.util.Set;
import java.util.TreeSet;
public class SetToArray1 {
public static void main(String[] args) {
//Constructs a new, empty set
Set<String> Set = new TreeSet<String>();
//add element in it
Set.add("java");
Set.add("php");
Set.add("android");
//display the element of Set
System.out.println("Set Elements : "+ Set);
String [] arr = new String[Set.size()];
int i =0;
for (String element : Set) {
arr[i++] = element;
}
//print array Element
for (String element : arr) {
System.out.println("Array Element is : "+element);
}
}
}
Output:
Set Elements : [android, java, php]
Array Element is : android
Array Element is : java
Array Element is : php
In this article we have learned about how to convert set to array in java. You can see more java TreeSet program for practice .
Reference :