在类里面,我们使用此代码通过整数流生成斐波那契序列。 有人可以向我解释一下 .map() 函数在这段代码中的作用吗?
public class fibStream {
public static Stream<Integer> getFibStream() {
return Stream.iterate(new Integer[] {0,1}, s -> new Integer[]{s[1], s[0] + s[1]})
.map(s -> s[0]); //what is .map() doing here?
}
}
最佳答案
由于种子 new Integer[] {0,1}
,您将使用两个元素迭代 Integer[]
。每一步都使用新的 Integer[]
进行迭代,并重新评估其值。
map
只是访问第一个Integer
以最终消耗(利用)它。
举个例子,更好的组合实现可能看起来像(打印 20 第一个斐波那契元素):
Stream.iterate(new Integer[] {0,1}, s -> new Integer[]{s[1], s[0] + s[1]})
.limit(20) // short-circuit
.map(s -> s[0])
.forEach(System.out::println); // consume the mapped element
Additional clarification; the fibonacci stream is made of arrays like
{0,1} {1,1} {1,2} {2,3} {3,5}
and.map(s -> s[0])
gets each array, returning the first number from them, like0 1 1 2 3
.
关于java - 在Java中使用Stream迭代斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55062083/