Convert List to array Using Stream in Java 8




List (using toArray() Method) can also be converted to an array using stream concept (Stream concept has been introduced in java 1.8 version).

Steps to convert list(using toArray() Method) into an array Using Stream

(1.) Use stream() method on list .
stream() method returns a stream with the collection as its source.
List<String> list = new ArrayList<String>();
list.add(“Raj”);
list.add(“Manish”);
Stream<String> s = list.stream();

(2.) Use toArray() method on the the stream obtained

Object []obj = s.toArray();

Demo Program to Convert list into an array Using Stream in Java 8

Example.java

package com.masterjavatutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) {
	      
		List<String> list = new ArrayList<String>;
		list.add("Delhi");
		list.add("Mumbai");
		list.add("Bangalore");
		list.add("Kolkatta");
		list.add("Patna");
		list.add("Lucknow");
		
		Stream<String> stream = list.stream();   
		Object[] array = stream.toArray(); 
		for(Object obj : array){
		   String str = (String)obj;
		   System.out.println(str); 
		}
		
	}

}

Output of the above Program is as below:

Delhi
Mumbai
Bangalore
Kolkatta
Patna
Lucknow