[英]What is the (kind of) inverse operation to Java's Stream.flatMap()?
[英]Is my understanding of Java Stream.flatMap correct?
我试图回答这个问题,但我没有回答,因为我不太了解 Streams。 请告诉我我的解释是否正确。
我的答案 :
import java.util.Arrays;
import java.util.stream.Stream;
public class Temp {
public static void main(String [] args){
String [] input = {"1,2", "3,4", "5"};
String [] expected = {"1", "2", "3", "4", "5"};
String [] actual = Stream.of(input)
.flatMap(s -> Arrays.stream(s.split(",")))
.toArray(String [] :: new);
//Testing - Runs only when assertions are enabled for your JVM. Set VM args = -ea for your IDE.
assert Arrays.equals(actual, expected) : "Actual array does not match expected array!";
}
}
我的解释:
1 - 取一个元素流(在这个例子中是字符串),一次将一个元素传递给flatMap
。
问题 -这实际上是一次一个元素吗?
2- flatMap
接受一个将元素转换为Stream
的Function
。 在示例中,该函数接受一个字符串(“1,2”)并将其转换为多个字符串(“1”、“2”)的流。 多个字符串的流由 Arrays.stream(an array) 生成,我们知道它接受一个数组并将其转换为流。 该数组由s.split(",")
。 所有其他元素都被处理并放入这个流中。
问题 - flatMap 是否为输入数组中的所有元素返回一个 Stream 或为输入数组的每个元素返回一个 Stream?
3 - toArray
在它从flatMap
获得的单个流中获取元素并将它们放入一个数组中。
平面地图的预定义语法是
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
where, R is the element type of the new stream.
Stream is an interface and T is the type
of stream elements. mapper is a stateless function
which is applied to each element and the function
returns the new stream.
那么 flatMap 内部是如何工作的呢?
它首先将返回另一个 Optional 的函数应用于内部对象(如果存在),然后在返回之前展平结果,因此您不必自己做。
它在内部定义了这样的东西
public static <T> Optional<T> flatten(Optional<Optional<T>> optional) {
return optional.orElse(Optional.empty());
}
所以在你的情况下
String [] actual = Stream.of(input)
.flatMap(s -> Arrays.stream(s.split(",")))
.toArray(String [] :: new);
StreamofInput(input) - taking input as collection
flatMap: adding map function
s-> Arrays.stream(s.split(","))- taking argument from your arrays individually which is represent by "s" , then converting your array which is splitted by "," and converting into stream.
toArray : converting you result into flat single array because its stateless so it will give you new collection.
更多你可以访问这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.