2017-11-27 19 views

答えて

4
public class Fibonacci { 

    public static void main(String[] args) { 
     IntStream stream = IntStream.generate(new FibonacciSupplier()); 
     stream.limit(20).forEach(System.out::println); 
    } 

    private static class FibonacciSupplier implements IntSupplier { 

     int current = 1; 
     int previous = 0; 

     @Override 
     public int getAsInt() { 
      int result = current; 
      current = previous + current; 
      previous = result; 
      return result; 
     } 
    } 
} 

注しかし、この流れは、すぐにあなたが第47回要素に達すると、無限ではないことを、値が正の整数に収めるには大きすぎます。

+0

をあなたがここに私のInstream.of方法を組み込むことができるだろうか? –

+2

もし私がしたら、あなたが尋ねたように無限の流れはありません。あなたはちょうど7つの値のストリームを持っています。 –

1

map操作を使用してシーケンスを生成する方法があると思われるかもしれません。存在しない:Java非終端操作は、設計上、一度に1つの要素に対してしか操作できません。これにより、それらを確定的な結果で並列ストリームに変換することができます。

最高のオプションは、無限のストリームを生成することです。これを行うには、いくつかの方法があります:

class Fib { 
    private int previous = 0; 
    private int current = 1; 

    private int next() { 
     int temp = previous + current; 
     previous = current; 
     current = temp; 
     return current; 
    } 

    public IntStream stream() { 
     return IntStream.generate(this::next); 
    } 
} 

new Fib().stream()として使用されています。

あなたは、同様の配列を使用してこれを行うことができます。

Stream.iterate(new int[]{0, 1}, a -> new int[]{a[1], a[0]+a[1]}).mapToInt(a -> a[1]) 
関連する問題