streams - Fibonacci sequence sum

本文介绍如何使用Java 8的Stream API中的iterate方法来生成斐波那契数列。通过设置初始值和迭代函数,可以轻松地创建无限斐波那契数列流,并通过skip和limit方法获取特定范围内的数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Stream.iterate() starts with a seed (the first argument) and passes it to the method (the second argument). The result is added to the stream and also stored for use as the first argument the next time iterate() is called, and so on.

// streams/Fibonacci.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.stream.*;

public class Fibonacci {
  int x = 1;

  Stream<Integer> numbers() {
    return Stream.iterate(
        0,
        i -> {
          int result = x + i;
          System.out.println("i:" + i + ", " + x);
          x = i;
          // System.out.println("i:" + i + ", " + x);
          return result;
        });
  }

  public static void main(String[] args) {
    new Fibonacci()
        .numbers()
        .skip(20) // Don't use the first 20
        .limit(10) // Then take 10 of them
        .forEach(System.out::println);
  }
}
/* Output:
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
*/

My output:

i:0, 1
i:1, 0
i:1, 1
i:2, 1
i:3, 2
i:5, 3
i:8, 5
i:13, 8
i:21, 13
i:34, 21
i:55, 34
i:89, 55
i:144, 89

i:233, 144
i:377, 233
i:610, 377
i:987, 610
i:1597, 987
i:2584, 1597
i:4181, 2584
6765
i:6765, 4181
10946
i:10946, 6765
17711
i:17711, 10946
28657
i:28657, 17711
46368
i:46368, 28657
75025
i:75025, 46368
121393
i:121393, 75025
196418
i:196418, 121393
317811
i:317811, 196418
514229

 The Fibonacci sequence sums the last two elements in the sequence to produce the next one. iterate() only remembers the result, so we must use x to keep track of the other element.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Fibonacci.java

3. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#iterate-T-java.util.function.UnaryOperator-

4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值