I tried the following code using Java 8 streams:
Arrays.asList("A", "B").stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().map(s1 -> s + s1)).collect(Collectors.toList());
What I get is a List<Object>
while I would expect a List<String>
. If I remove the collect and I try:
Arrays.asList("A", "B").stream().flatMap(s -> Arrays.asList("X", "Y").stream().map(s1 -> s + s1));
I correctly get a Stream<String>
.
Where am I wrong? Can someone help me?
Many thanks in advance.
Edit:
The problem is due to Eclipse (now using Kepler SR2 with java 8 patch 1.0.0.v20140317-1956). The problem does non appear if compiling using javac or, as commented by Holger, using Netbeans
Java 8 example of Stream.flatMap () function to get a single List containing all elements from a list of lists. This program uses flatMap () operation to convert List<List<Integer>> to List<Integer>. Program output. Java 8 example of Stream.flatMap () function to get a single List containing all elements from a array of arrays.
After the Java 16 release, we can now invoke toList (), a new method directly on the Stream, to get the List. Libraries like StreamEx also provide a convenient way to get a List directly from a Stream. Stream.collect ( Collectors.toUnmodifiableList ()): Since Java 10 We'll work with the methods in the chronological order of their release. 3.
We can use Stream collect () function to perform a mutable reduction operation and concatenate the list elements.
Java Stream collect () is mostly used to collect the stream elements to a collection. It’s a terminal operation. It takes care of synchronization when used with a parallel stream. The Collectors class provides a lot of Collector implementation to help us out. Want to learn more? Join the DigitalOcean Community!
Type inference is a new feature. Until tools and IDEs are fully developed I recommend using explicitly typed lambdas. There ware cases where Eclipse even crashed if an explicit cast was missing, but that is fixed now.
Here's a workaround:
With a typed "s1":
asList.stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().map((String s1) -> s + s1))
.collect(Collectors.toList());
Or with a genric parameter:
asList.stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().<String>map(s1 -> s + s1))
.collect(Collectors.toList());
The same is true if you add the parameter before flatMap
instead of map
.
But I suggest you use s::concat
:
asList.stream()
.flatMap(s -> Arrays.asList("X", "Y").stream().map(s::concat))
.collect(Collectors.toList());
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