「java8」Stream.iterate()メソッドでフィボナッチ数列を生成するサンプル

2020年12月11日

Javaコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
import java.util.stream.Stream;
public class FibonacciDemo {
public static final int MAX = 15;
public static void main(String[] args) {
System.out.println("フィボナッチ数列のサンプル");
Stream.iterate(new int[] { 0, 1 }, cft -> new int[] { cft[1], cft[0] + cft[1] })
.limit(MAX)
.map(n -> n[0])
.forEach(res -> System.out.println(res));
}
}
package com.arkgame.study; import java.util.stream.Stream; public class FibonacciDemo { public static final int MAX = 15; public static void main(String[] args) { System.out.println("フィボナッチ数列のサンプル"); Stream.iterate(new int[] { 0, 1 }, cft -> new int[] { cft[1], cft[0] + cft[1] }) .limit(MAX) .map(n -> n[0]) .forEach(res -> System.out.println(res)); } }
package com.arkgame.study;

import java.util.stream.Stream;

public class FibonacciDemo {

      public static final int MAX = 15;

      public static void main(String[] args) {

            System.out.println("フィボナッチ数列のサンプル");
            Stream.iterate(new int[] { 0, 1 }, cft -> new int[] { cft[1], cft[0] + cft[1] })
                        .limit(MAX)
                        .map(n -> n[0])
                        .forEach(res -> System.out.println(res));
      }

}

実行結果
フィボナッチ数列のサンプル
0
1
1
2
3
5
8
13
21
34
55
89
144
233

Java

Posted by arkgame