java - 在Java中使用Stream迭代斐波那契数列

标签 java loops dictionary java-stream

在类里面,我们使用此代码通过整数流生成斐波那契序列。 有人可以向我解释一下 .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

来自comments by JollyJoker

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, like 0 1 1 2 3.

关于java - 在Java中使用Stream迭代斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55062083/

相关文章:

c++ - 每秒编码 60 次 C++

python-3.x - 将字典反转为键 : list of values?

php - 如何使图像 map <Area> 标签具有背景色

java - 在 for 循环中绘制图像 x 次

r - 根据多列中的直接和间接相似性对变量进行分组的快速方法

python - 创建一个 python 循环,其中输入是随机数

string - 垃圾回收和Go中指针的正确用法

java - JSP 单击按钮时运行方法

java - 索引越界异常,我写的函数挂掉了

java - 使用代理时连接重置