2017-11-27 11 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 비 터미널 조작은 설계 상 한 x에 한 요소 만 조작 할 수 있습니다. 이를 통해 결정 성있는 결과로 병렬 스트림으로 변환 할 수 있습니다.

가장 좋은 옵션은 무한 스트림을 생성하는 것입니다.

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])