Lets assume I have a class containing a List, e.g.
public static class ListHolder {
List<String> list = new ArrayList<>();
public ListHolder(final List<String> list) {
this.list = list;
}
public List<String> getList() {
return list;
}
}
Let's furthermore assume I have a whole list of instances of this class:
ListHolder listHolder1 = new ListHolder(Arrays.asList("String 1", "String 2"));
ListHolder listHolder2 = new ListHolder(Arrays.asList("String 3", "String 4"));
List<ListHolder> holders = Arrays.asList(listHolder1, listHolder2);
And now I need to extract all Strings to get a String List containing all Strings of all instances, e.g.:
[String 1, String 2, String 3, String 4]
With Guava this would look like this:
List<String> allString = FluentIterable
.from(holders)
.transformAndConcat(
new Function<ListHolder, List<String>>() {
@Override
public List<String> apply(final ListHolder listHolder) {
return listHolder.getList();
}
}
).toList();
My question is how can I achieve the same with the Java 8 stream API?
List<String> allString = holders.stream()
.flatMap(h -> h.getList().stream())
.collect(Collectors.toList());
Here is an older question about collection flattening: (Flattening a collection)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With