Created
June 23, 2025 18:02
-
-
Save robtimus/4970e5841ec92c9b11e6e571d5ed6e7a to your computer and use it in GitHub Desktop.
Creating streams of Fibonacci numbers using Gatherers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Fibonacci.java | |
* Copyright 2025 Rob Spoor | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
import java.util.stream.Gatherer; | |
import java.util.stream.IntStream; | |
import java.util.stream.Stream; | |
final class Fibonacci { | |
private Fibonacci() { | |
} | |
public static Stream<Integer> stream() { | |
return IntStream.generate(() -> 0) | |
.boxed() | |
.gather(Gatherer.ofSequential(() -> new int[2], (state, _, downstream) -> { | |
if (state[1] == 0) { | |
state[0] = 0; | |
state[1] = 1; | |
downstream.push(0); | |
downstream.push(1); | |
} | |
int value = state[0] + state[1]; | |
state[0] = state[1]; | |
state[1] = value; | |
return downstream.push(value); | |
})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment