繁体   English   中英

相当于 Java 8 中 Scala 的 foldLeft

[英]Equivalent of Scala's foldLeft in Java 8

Java 8 中 Scala 的foldLeft相当于什么?

我很想认为它是reduce ,但是 reduce 必须返回与它所减少的相同类型的东西。

例子:

import java.util.List;

public class Foo {

    // this method works pretty well
    public int sum(List<Integer> numbers) {
        return numbers.stream()
                      .reduce(0, (acc, n) -> (acc + n));
    }

    // this method makes the file not compile
    public String concatenate(List<Character> chars) {
        return chars.stream()
                    .reduce(new StringBuilder(""), (acc, c) -> acc.append(c)).toString();
    }
}

在上面的代码中的问题是acc umulator: new StringBuilder("")

因此,有人可以指出我正确的foldLeft /fix my code 等价物吗?

Java 8 的 Stream API 中没有foldLeft等价物。 正如其他人所指出的, reduce(identity, accumulator, combiner)接近,但它与foldLeft不等价,因为它需要结果类型B与自身组合并具有关联性( foldLeft ,类似于幺半群),一个属性不每种类型都有。

对此还有一个增强请求:添加Stream.foldLeft()终端操作

要了解为什么 reduce 不起作用,请考虑以下代码,您打算在其中执行一系列以给定数字开头的算术运算:

val arithOps = List(('+', 1), ('*', 4), ('-', 2), ('/', 5))
val fun: (Int, (Char, Int)) => Int = {
  case (x, ('+', y)) => x + y
  case (x, ('-', y)) => x - y
  case (x, ('*', y)) => x * y
  case (x, ('/', y)) => x / y
}
val number = 2
arithOps.foldLeft(number)(fun) // ((2 + 1) * 4 - 2) / 5

如果您尝试编写reduce(2, fun, combine) ,您可以传递什么组合器函数来组合两个数字? 将两个数字加在一起显然不能解决问题。 此外,值2显然不是标识元素。

请注意,任何需要顺序执行的操作都不能用reduce表示。 foldLeft实际上比reduce更通用:您可以使用foldLeft实现reduce ,但不能使用reduce实现foldLeft

更新:

这是修复代码的初步尝试:

public static String concatenate(List<Character> chars) {
        return chars
                .stream()
                .reduce(new StringBuilder(),
                                StringBuilder::append,
                                StringBuilder::append).toString();
    }

它使用以下reduce方法

<U> U reduce(U identity,
                 BiFunction<U, ? super T, U> accumulator,
                 BinaryOperator<U> combiner);

这听起来可能令人困惑,但如果您查看 javadoc,有一个很好的解释可以帮助您快速掌握细节。 减少相当于以下代码:

U result = identity;
for (T element : this stream)
     result = accumulator.apply(result, element)
return result;

如需更深入的解释,请查看此来源

但是这种用法是不正确的,因为它违反了 reduce 的约定,其中规定累加器应该是一个关联的、无干扰的、无状态的函数,用于将附加元素合并到结果中 换句话说,由于身份是可变的,因此在并行执行的情况下结果将被破坏。

正如下面的评论中所指出的,正确的选项是使用如下缩减:

return chars.stream().collect(
     StringBuilder::new, 
     StringBuilder::append, 
     StringBuilder::append).toString();

供应商StringBuilder::new将用于创建可重用的容器,这些容器稍后将被合并。

您正在寻找的方法是java.util.Stream.reduce ,特别是具有三个参数、标识、累加器和二元函数的重载。 这是 Scala 的foldLeft的正确等价物。

但是,你不能使用Java的reduce这种方式,也没有Scala的foldLeft对这一问题。 改用collect

它可以通过使用收集器来完成:

public static <A, B> Collector<A, ?, B> foldLeft(final B init, final BiFunction<? super B, ? super A, ? extends B> f) {
    return Collectors.collectingAndThen(
            Collectors.reducing(Function.<B>identity(), a -> b -> f.apply(b, a), Function::andThen),
            endo -> endo.apply(init)
    );
}

用法示例:

IntStream.rangeClosed(1, 100).boxed().collect(foldLeft(50, (a, b) -> a - b));  // Output = -5000

对于您的问题,这符合您的要求:

public String concatenate(List<Character> chars) {
        return chars.stream()
                .collect(foldLeft(new StringBuilder(), StringBuilder::append)).toString();
}

其他人是正确的,但没有等价物。 这是一个接近的实用程序-

<U, T> U foldLeft(Collection<T> sequence, U identity, BiFunction<U, ? super T, U> accumulator) {
    U result = identity;
    for (T element : sequence)
        result = accumulator.apply(result, element);
    return result;
}

您使用上述方法的情况看起来像-

public String concatenate(List<Character> chars) {
    return foldLeft(chars, new StringBuilder(""), StringBuilder::append).toString();
}

或者没有 lambda 方法引用糖,

public String concatenate(List<Character> chars) {
    return foldLeft(chars, new StringBuilder(""), (stringBuilder, character) -> stringBuilder.append(character)).toString();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM