相关疑难解决方法(0)

为什么在java 8中转换类型的reduce方法需要一个组合器

我无法完全理解combinerStreams reduce方法中实现的角色.

例如,以下代码不编译:

int length = asList("str1", "str2").stream()
            .reduce(0, (accumulatedInt, str) -> accumulatedInt + str.length());
Run Code Online (Sandbox Code Playgroud)

编译错误说:( 参数不匹配; int无法转换为java.lang.String)

但是这段代码确实编译:

int length = asList("str1", "str2").stream()  
    .reduce(0, (accumulatedInt, str ) -> accumulatedInt + str.length(), 
                (accumulatedInt, accumulatedInt2) -> accumulatedInt + accumulatedInt2);
Run Code Online (Sandbox Code Playgroud)

我知道组合器方法用于并行流 - 所以在我的例子中它将两个中间累积的int加在一起.

但是我不明白为什么第一个例子在没有组合器的情况下编译或者组合器如何解决字符串到int的转换,因为它只是将两个整数加在一起.

任何人都可以阐明这一点吗?

java java-8 java-stream

123
推荐指数
3
解决办法
3万
查看次数

Java 8中Scala的foldLeft的等价物

Scala foldLeft在Java 8中的优势是什么?

我很想想它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();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面代码中的问题是accumulator:new StringBuilder("")

因此,任何人都可以指出我正确的foldLeft/修复我的代码?

java reduce java-8 foldleft

22
推荐指数
4
解决办法
2万
查看次数

标签 统计

java ×2

java-8 ×2

foldleft ×1

java-stream ×1

reduce ×1