Created
June 29, 2025 02:04
-
-
Save rokon12/880b8189ecf2285ccf08ddb910322892 to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - snippet-8.java
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
| public static Gatherer<Double, ?, Double> movingAverage(int windowSize) { | |
| return Gatherer.of( | |
| LinkedList::new, // 1️⃣ Use LinkedList for efficient add/remove | |
| (window, price, downstream) -> { | |
| window.add(price); // 2️⃣ Add new price to window | |
| if (window.size() > windowSize) { // 3️⃣ Window too big? | |
| window.removeFirst(); // 4️⃣ Remove oldest price | |
| } | |
| if (window.size() == windowSize) { // 5️⃣ Window full? | |
| double avg = window.stream() | |
| .mapToDouble(Double::doubleValue) | |
| .average() | |
| .orElse(0.0); | |
| return downstream.push(avg); // 6️⃣ Emit moving average | |
| } | |
| return true; // 7️⃣ Keep gathering (building up window) | |
| } | |
| ); | |
| } | |
| // Usage example: | |
| // Prices: [100, 102, 101, 105, 103, 107, 104] | |
| // Window size 3: | |
| // [100, 102, 101] → avg: 101.0 | |
| // [102, 101, 105] → avg: 102.7 | |
| // [101, 105, 103] → avg: 103.0 | |
| // ... sliding window continues |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment