Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Turn a Stream of Arrays to Single Stream in Java
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<>();
}
}
@hendrixjoseph

This comment has been minimized.

Copy link
Owner Author

commented Jun 14, 2019

I reference this Gist in my blog post of the same name Turn a Stream of Arrays to Single Stream in Java.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.