Skip to content

Instantly share code, notes, and snippets.

@rokon12
Created June 29, 2025 02:17
Show Gist options
  • Save rokon12/2773fd9871ec329fdc22cb1f63e23848 to your computer and use it in GitHub Desktop.
Save rokon12/2773fd9871ec329fdc22cb1f63e23848 to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - snippet-8.java
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