与Java 8中的Scala的foldLeft等效 [英] Equivalent of Scala's foldLeft in Java 8

查看:122
本文介绍了与Java 8中的Scala的foldLeft等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala在Java 8中出色的foldLeft等效于什么?

What is the equivalent of of Scala's great foldLeft in Java 8?

我很想以为它是reduce,但是reduce必须返回与reduce相同的类型.

I was tempted to think it was reduce, but reduce has to return something of identical type to what it reduces on.

示例:

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("")

The problem in the code above is the accumulator: new StringBuilder("")

因此,有人可以指出我与foldLeft/修复我的代码的正确含义吗?

Thus, could anyone point me to the proper equivalent of the foldLeft/fix my code?

推荐答案

更新:

这是修复您的代码的最初尝试:

Here is initial attempt to get your code fixed:

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

它使用以下这听起来可能令人困惑,但是如果您查看javadocs,会有一个不错的解释,可以帮助您快速掌握细节.减少量等效于以下代码:

It may sound confusing but if you look at the javadocs there is a nice explanation that may help you quickly grasp the details. The reduction is equivalent to the following code:

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

有关更深入的说明,请检查此来源.

For a more in-depth explanation please check this source.

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

This usage is not correct though because it violates the contract of reduce which states that the accumulator should be an associative, non-interfering, stateless function for incorporating an additional element into a result. In other words since the identity is mutable the result will be broken in case of parallel execution.

正如下面评论中所指出的那样,正确的选择是按如下方式使用减少量:

As pointed in the comments below a correct option is using the reduction as follows:

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

供应商StringBuilder::new将用于创建可重复使用的容器,然后将其合并.

The supplier StringBuilder::new will be used to create reusable containers which will be later combined.

这篇关于与Java 8中的Scala的foldLeft等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆