潜在无限流的功能解压缩实现

时间:2016-03-10 15:07:22

标签: java functional-programming java-8 java-stream

我已按照以下方式实施了功能unzip()操作:

public static <T, U, V> Tuple2<Stream<U>, Stream<V>> unzip(
        Stream<T> stream, 
        Function<T, Tuple2<U, V>> unzipper) {

    return stream.map(unzipper)
        .reduce(new Tuple2<>(Stream.<U>empty(), Stream.<V>empty()),
            (unzipped, tuple) -> new Tuple2<>(
                Stream.concat(unzipped.$1(), Stream.of(tuple.$1())),
                Stream.concat(unzipped.$2(), Stream.of(tuple.$2()))),
            (unzipped1, unzipped2) -> new Tuple2<>(
                Stream.concat(unzipped1.$1(), unzipped2.$1()),
                Stream.concat(unzipped1.$2(), unzipped2.$2())));
}

这很好,因为输入流没有很多元素。这是因为访问深度连接的流的元素可能导致StackOverflowException。根据{{​​3}}:

  

实施说明:

     

从重复串联构造流时要小心。访问深度连接的流的元素可能会导致深度调用链,甚至StackOverflowException

对于少数元素,我的unzip实现有效。鉴于课程Person

class Person {

    public final String name;

    public final int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

如果我有一群人:

Stream<Person> people = Stream.of(
    new Person("Joe", 52), 
    new Person("Alan", 34), 
    new Person("Peter", 42));

我可以这样使用我的unzip()实现:

Tuple2<Stream<String>, Stream<Integer>> result = StreamUtils.unzip(people, 
        person -> new Tuple2<>(person.name, person.age));

List<String> names = result.$1()
    .collect(Collectors.toList()); // ["Joe", "Alan", "Peter"]
List<Integer> ages = result.$2()
    .collect(Collectors.toList()); // [52, 34, 42]

哪个是正确的。

所以我的问题是: unzip()是否有办法处理许多元素(可能是无限的)?

注意:为了完整性,这里是我的不可变Tuple2类:

public final class Tuple2<A, B> {

    private final A $1;

    private final B $2;

    public Tuple2(A $1, B $2) {
        this.$1 = $1;
        this.$2 = $2;
    }

    public A $1() {
        return $1;
    }

    public B $2() {
        return $2;
    }
}

1 个答案:

答案 0 :(得分:4)

您的解决方案不仅容易出现潜在的StackOverflowError,而且远离处理潜在的无限流,即使StackOverflowError的风险不存在。关键是,您正在构建一个流,但它是一个连接的单个元素流的流,一个用于源流的每个元素。换句话说,在返回unzip方法时,您将拥有一个完全具体化的数据结构,这将消耗比收集到ArrayList或简单toArray()操作的结果更多的内存。 / p>

然而,当你想要在之后执行collect时,支持潜在无限流的想法无论如何都是没有意义的,因为收集意味着处理所有元素而没有短路。

一旦你放弃了支持无限流的想法并专注于收集操作,就会有一个更简单的解决方案。从this solution获取代码,将Pair替换为Tuple2并将累加器逻辑从“条件”更改为“两者”,我们得到:

public static <T, A1, A2, R1, R2> Collector<T, ?, Tuple2<R1,R2>> both(
    Collector<T, A1, R1> first, Collector<T, A2, R2> second) {

    Supplier<A1> s1=first.supplier();
    Supplier<A2> s2=second.supplier();
    BiConsumer<A1, T> a1=first.accumulator();
    BiConsumer<A2, T> a2=second.accumulator();
    BinaryOperator<A1> c1=first.combiner();
    BinaryOperator<A2> c2=second.combiner();
    Function<A1,R1> f1=first.finisher();
    Function<A2,R2> f2=second.finisher();
    return Collector.of(
        ()->new Tuple2<>(s1.get(), s2.get()),
        (p,t)->{ a1.accept(p.$1(), t); a2.accept(p.$2(), t); },
        (p1,p2)->new Tuple2<>(c1.apply(p1.$1(), p2.$1()), c2.apply(p1.$2(), p2.$2())),
        p -> new Tuple2<>(f1.apply(p.$1()), f2.apply(p.$2())));
}

这可以像

一样使用
Tuple2<List<String>, List<Integer>> namesAndAges=
    Stream.of(new Person("Joe", 52), new Person("Alan", 34), new Person("Peter", 42))
        .collect(both(
            Collectors.mapping(p->p.name, Collectors.toList()),
            Collectors.mapping(p->p.age,  Collectors.toList())));
List<String> names = namesAndAges.$1(); // ["Joe", "Alan", "Peter"]
List<Integer> ages = namesAndAges.$2(); // [52, 34, 42]

链接答案的陈述也在这里。您可以在收集器中执行几乎所有可以表示为流操作的内容。

如果您希望通过函数更接近原始代码,从stream元素映射到Tuple2,您可以将上面的解决方案包含在

public static <T, T1, T2, A1, A2, R1, R2> Collector<T, ?, Tuple2<R1,R2>> both(
    Function<? super T, ? extends Tuple2<? extends T1, ? extends T2>> f,
    Collector<T1, A1, R1> first, Collector<T2, A2, R2> second) {

    return Collectors.mapping(f, both(
            Collectors.mapping(Tuple2::$1, first),
            Collectors.mapping(Tuple2::$2, second)));
}

并像

一样使用它
Tuple2<List<String>, List<Integer>> namesAndAges=
    Stream.of(new Person("Joe", 52), new Person("Alan", 34), new Person("Peter", 42))
        .collect(both(
            p -> new Tuple2<>(p.name, p.age), Collectors.toList(), Collectors.toList()));

您可能会识别函数p -> new Tuple2<>(p.name, p.age),就像您传递给unzip方法的函数一样。上述解决方案是懒惰的,但需要在“解压缩”之后的操作表示为收集器。如果您想要Stream代替并且接受解决方案的非延迟性质,就像您原来的unzip操作一样,但希望它比concat更有效,您可以使用:

public static <T, U, V> Tuple2<Stream<U>, Stream<V>> unzip(
    Stream<T> stream,  Function<T, Tuple2<U, V>> unzipper) {

    return stream.map(unzipper)
        .collect(Collector.of(()->new Tuple2<>(Stream.<U>builder(), Stream.<V>builder()),
            (unzipped, tuple) -> {
                unzipped.$1().accept(tuple.$1()); unzipped.$2().accept(tuple.$2());
            },
            (unzipped1, unzipped2) -> {
                unzipped2.$1().build().forEachOrdered(unzipped1.$1());
                unzipped2.$2().build().forEachOrdered(unzipped1.$2());
                return unzipped1;
            },
            tuple -> new Tuple2<>(tuple.$1().build(), tuple.$2().build())
        ));
}

这可以替代基于concat的解决方案。它还将完全存储流元素,但它将使用Stream.Builder,该Stream针对逐步填充和使用一次(在ArrayList操作中)的用例进行了优化。这比收集到toArray()(至少使用参考实现)更有效,因为它使用“spined buffer”,在增加容量时不需要复制。对于可能未知大小的流,这是最有效的解决方案(对于已知大小的流,private int a; public MobileEmitter(double launchAngle, double launchAngleVariation, int a) { super(launchAngle, launchAngleVariation); this.a = a; } 将表现得更好)。