Flatten a Stream of Arrays in Java using forEach loop
Last Updated :
11 Dec, 2018
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method.
Examples:
Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }}
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}}
Output: [G, e, e, k, s, F, o, r]
Approach:
- Get the Arrays in the form of 2D array.
- Create an empty list to collect the flattened elements.
- With the help of forEach loop, convert each elements of the array into stream and add it to the list
- Now convert this list into stream using stream() method.
- Now flatten the stream by converting it into array using toArray() method.
Below is the implementation of the above approach:
Example 1: Using arrays of integer.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
class GFG {
public static <T> Stream<T> flattenStream(T[][] arrays)
{
List<T> list = new ArrayList<>();
for (T[] array : arrays) {
Arrays.stream(array)
.forEach(list::add);
}
return list.stream();
}
public static void main(String[] args)
{
Integer[][] arr = {
{ 1 , 2 },
{ 3 , 4 , 5 , 6 },
{ 7 , 8 , 9 }
};
Integer[] flatArray = flattenStream(arr)
.toArray(Integer[] :: new );
System.out.println(Arrays.toString(flatArray));
}
}
|
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2: Using arrays of Characters.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
class GFG {
public static <T> Stream<T> flattenStream(T[][] arrays)
{
List<T> list = new ArrayList<>();
for (T[] array : arrays) {
Arrays.stream(array)
.forEach(list::add);
}
return list.stream();
}
public static void main(String[] args)
{
Character[][] arr = {
{ 'G' , 'e' , 'e' , 'k' , 's' },
{ 'F' , 'o' , 'r' },
{ 'G' , 'e' , 'e' , 'k' , 's' }
};
Character[] flatArray = flattenStream(arr)
.toArray(Character[] :: new );
System.out.println(Arrays.toString(flatArray));
}
}
|
Output:
[G, e, e, k, s, F, o, r, G, e, e, k, s]
Share your thoughts in the comments
Please Login to comment...