我对Java Stream.flatMap的理解正确吗?

时间:2020-03-05 06:37:53

标签: java lambda java-stream

我试图回答question,但是我没有回答,因为我对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-获取元素流(在此示例中为Strings),然后一次将一个元素传递给flatMap

问题-实际上一次是一个元素吗?

2-{{​​1}}采用flatMap,它将元素转换为Function。在示例中,该函数采用一个字符串(“ 1,2”),并将其转换为多个字符串(“ 1”,“ 2”)的流。多个字符串流是由Arrays.stream(一个数组)生成的,我们知道该数组接受一个数组并将其转换为流。该数组是由Stream生成的。所有其他元素都将被处理并放入这一流中。

问题- flatMap是否为输入数组中的所有元素返回一个Stream或为输入数组中的每个元素返回一个Stream?

3-s.split(",")将从toArray获得的单个数据流中的元素放入一个数组中。

1 个答案:

答案 0 :(得分:0)

平面地图的预定义语法是

<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.

有关更多信息,您可以访问here