How To Get ArrayList From Stream in Java 8 | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

1. Using Collectors.toList() method

package com.codeFactory;

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

/**
 * @author code.factory
 *
 */
public class ArrayListFromStream {

	public static void main(String... args) {
		Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
		
		ArrayList<Integer> arrayList = getArrayListFromStream(stream);
		
		System.out.println("ArrayList : " + arrayList);
	}
	
	private static <T> ArrayList<T> getArrayListFromStream(Stream<T> stream) {
		return new ArrayList<T>(stream.collect(Collectors.toList()));
	}
}

Output :

ArrayList : [1, 2, 3, 4, 5]

2. Using Collectors.toCollection() method

package com.codeFactory;

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

/**
 * @author code.factory
 *
 */
public class ArrayListFromStream {

	public static void main(String... args) {
		Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
		
		ArrayList<Integer> arrayList = getArrayListFromStream(stream);
		
		System.out.println("ArrayList : " + arrayList);
	}
	
	private static <T> ArrayList<T> getArrayListFromStream(Stream<T> stream) {
		return new ArrayList<T>(stream.collect(Collectors.toCollection(ArrayList::new)));
	}
}


Output :

ArrayList : [1, 2, 3, 4, 5]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s