Java program to get ArrayList from Stream

Given a Stream, the task is to convert this Stream into ArrayList in Java 8.

Examples:

Input: Stream: [1, 2, 3, 4, 5]
Output: ArrayList: [1, 2, 3, 4, 5]

Input: Stream: ['G', 'e', 'e', 'k', 's']
Output: ArrayList: ['G', 'e', 'e', 'k', 's'

1. Using Collectors.toList() method:

  1. Get the Stream to be converted.
  2. Collect the stream as List using collect() and Collectors.toList() methods.
  3. Convert this List into an ArrayList
  4. Return/Print the ArrayList

Below is the implementation of the above approach:

Program:

// Java program to convert Stream to ArrayList
// using Collectors.toList() method

import java.util.*;
import java.util.stream.*;

public class GFG {

	// Function to get ArrayList from Stream
	public static  ArrayList
	getArrayListFromStream(Stream stream)
	{

		// Convert the Stream to List
		List
			list = stream.collect(Collectors.toList());

		// Create an ArrayList of the List
		ArrayList
			arrayList = new ArrayList(list);

		// Return the ArrayList
		return arrayList;
	}

	// Driver code
	public static void main(String args[])
	{

		Stream
			stream = Stream.of(1, 2, 3, 4, 5);

		// Convert Stream to ArrayList in Java
		ArrayList
			arrayList = getArrayListFromStream(stream);

		// Print the arraylist
		System.out.println("ArrayList: " + arrayList);
	}
}

Output:

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

2.Using Collectors.toCollection() method:

Approach:

  1. Get the Stream to be converted.
  2. Collect the stream as ArrayList using collect() and Collectors.toCollection() methods.
  3. Return/Print the ArrayList

Below is the implementation of the above approach:

// Java program to convert Stream to ArrayList
// using Collectors.toList() method

import java.util.*;
import java.util.stream.*;

public class GFG {

	// Function to get ArrayList from Stream
	public static  ArrayList
	getArrayListFromStream(Stream stream)
	{

		// Convert the Stream to ArrayList
		ArrayList
			arrayList = stream
							.collect(Collectors
							.toCollection(ArrayList::new));

		// Return the ArrayList
		return arrayList;
	}

	// Driver code
	public static void main(String args[])
	{

		Stream
			stream = Stream.of(1, 2, 3, 4, 5);

		// Convert Stream to ArrayList in Java
		ArrayList
			arrayList = getArrayListFromStream(stream);

		// Print the arraylist
		System.out.println("ArrayList: "
						+ arrayList);
	}
}

 

Submit Your Programming Assignment Details