Java - How to convert Set to array

Posted on October 23, 2016


We can convert the Set into array by using

  • Set.toArray() method
  • Stream (Introduced in Java8)

SetToArrayExample.java

package com.boraji.tutorial;

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

/**
 * @author imssbora
 *
 */
public class SetToArrayExample {
	public static void main(String[] args) {
		//List to be converted into array
		Set<String> set=new HashSet<>();
		set.add("A");
		set.add("B");
		set.add("C");
		set.add("D");
		set.add("E");
		
		
		/*Method - 1 (Set.toArray())*/
		String[] array1=set.toArray(new String[set.size()]);
		System.out.println("\nMethod -1 Output:");
		for (String string : array1) {
			System.out.println(string);
		}
		
		/*Method - 2 (Using stream)*/
		String[] array2=set.stream().toArray(String[]::new);
		System.out.println("\nMethod -2 Output:");
		for (String string : array2) {
			System.out.println(string);
		}
	}
}

Output

Method -1 Output:
A
B
C
D
E

Method -2 Output:
A
B
C
D
E