Last Updated : 17 Jul, 2024
Given a Stream, the task is to convert this Stream into ArrayList in Java 8.
Examples:
Input: Stream: [1, 2, 3, 4, 5]1. Using Collectors.toList() method:
Output: ArrayList: [1, 2, 3, 4, 5]Input: Stream: ['G', 'e', 'e', 'k', 's']
Output: ArrayList: ['G', 'e', 'e', 'k', 's']
Approach:
Below is the implementation of the above approach.
Program: Java
// Java program to convert Stream to ArrayList
// using Collectors.toList() method
import java.util.*;
import java.util.stream.*;
public class GFG {
// Driver code
public static void main(String args[])
{
Stream<Integer>
stream = Stream.of(1, 2, 3, 4, 5);
// Convert Stream to ArrayList in Java
ArrayList<Integer>
arrayList = new ArrayList<Integer>(stream.collect(Collectors.toList()));
// Print the arraylist
System.out.println("ArrayList: " + arrayList);
}
}
ArrayList: [1, 2, 3, 4, 5]Explanation of the Program:
Collectors.toList
method. main
method, a Stream of integers is created and then collected into a List, which is used to initialize an ArrayList. Approach:
Below is the implementation of the above approach.
Program: Java
// 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 <T> ArrayList<T>
getArrayListFromStream(Stream<T> stream)
{
// Convert the Stream to ArrayList
ArrayList<T>
arrayList = stream
.collect(Collectors
.toCollection(ArrayList::new));
// Return the ArrayList
return arrayList;
}
// Driver code
public static void main(String args[])
{
Stream<Integer>
stream = Stream.of(1, 2, 3, 4, 5);
// Convert Stream to ArrayList in Java
ArrayList<Integer>
arrayList = getArrayListFromStream(stream);
// Print the arraylist
System.out.println("ArrayList: "
+ arrayList);
}
}
ArrayList: [1, 2, 3, 4, 5]Explanation of the Program:
Collectors.toCollection
method. getArrayListFromStream
function takes a Stream as input, collects its elements into an ArrayList, and returns it. main
method, a Stream of integers is converted into an ArrayList and printed.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4