Skip to content

Instantly share code, notes, and snippets.

@hendrixjoseph
Created June 14, 2019 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hendrixjoseph/4390fbec51965f3d7815717be153935d to your computer and use it in GitHub Desktop.
Save hendrixjoseph/4390fbec51965f3d7815717be153935d to your computer and use it in GitHub Desktop.
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
Copy link
Author

hendrixjoseph 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