Created
June 14, 2019 00:13
-
-
Save hendrixjoseph/4390fbec51965f3d7815717be153935d to your computer and use it in GitHub Desktop.
Turn a Stream of Arrays to Single Stream in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
public class ArrayHolder { | |
public static void main(final String... args) { | |
// An array of objects that have an array as a field... | |
final ArrayHolder[] holders = {new ArrayHolder(), new ArrayHolder(), new ArrayHolder(), new ArrayHolder()}; | |
// Go through each element in each array the pre-Java 8 way: | |
for (ArrayHolder holder : holders) { | |
for (Object object : holder.getArray()) { | |
// do the thing | |
} | |
} | |
// Do it with Java 8 Streams: | |
Arrays.stream(holders) | |
.map(ArrayHolder::getArray) | |
.flatMap(Arrays::stream) | |
.forEach(System.out::println); | |
// Works with lists, too. | |
final List<ArrayHolder> holderList = Arrays.asList(holders); | |
holderList.stream() | |
.map(ArrayHolder::getArray) | |
.flatMap(Arrays::stream) | |
.forEach(System.out::println); | |
// If your class has lists instead of arrays, | |
// call the List.stream() method in the flatMap | |
// method instead: | |
holderList.stream() | |
.map(ArrayHolder::getList) | |
.flatMap(List::stream) | |
.forEach(System.out::println); | |
// flatMap has compilation errors | |
// The method flatMap(Function<? super ArrayHolder,? extends Stream<? extends R>>) | |
// in the type Stream<ArrayHolder> is not applicable for the arguments (ArrayHolder::getArray) | |
// | |
// The type of getArray() from the type ArrayHolder is Object[], | |
// this is incompatible with the descriptor's return type: Stream<? extends R> | |
holderList.stream() | |
.flatMap(ArrayHolder::getArray); | |
// flatMap has compilation errors | |
// The method flatMap(Function<? super ArrayHolder,? extends Stream<? extends R>>) | |
// in the type Stream<ArrayHolder> is not applicable for the arguments (ArrayHolder::getList) | |
// | |
// The type of getList() from the type ArrayHolder is List<Object>, | |
// this is incompatible with the descriptor's return type: Stream<? extends R> | |
holderList.stream() | |
.flatMap(ArrayHolder::getList); | |
// Works with 2D arrays as well: | |
final Object[][] objects = new Object[2][2]; | |
Arrays.stream(objects) | |
.flatMap(Arrays::stream); | |
} | |
public Object[] getArray() { | |
return new Object[5]; | |
} | |
public List<Object> getList() { | |
return new ArrayList<>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I reference this Gist in my blog post of the same name Turn a Stream of Arrays to Single Stream in Java.