java
41 lines · 7 steps
A rolling average over a sliding window
Maintain the mean of the last N readings in O(1) per update by tracking a running sum and a bounded deque.
Explained by
highlit
1import java.util.ArrayDeque;
2import java.util.Deque;
3
4public final class RollingAverage {
5
6 private final int windowSize;
7 private final Deque<Double> window = new ArrayDeque<>();
8 private double sum;
9
10 public RollingAverage(int windowSize) {
11 if (windowSize <= 0) {
12 throw new IllegalArgumentException("windowSize must be positive");
13 }
14 this.windowSize = windowSize;
15 }
16
17 public double add(double reading) {
18 window.addLast(reading);
19 sum += reading;
20 if (window.size() > windowSize) {
21 sum -= window.removeFirst();
22 }
23 return average();
24 }
25
26 public double average() {
27 if (window.isEmpty()) {
28 return Double.NaN;
29 }
30 return sum / window.size();
31 }
32
33 public boolean isFull() {
34 return window.size() == windowSize;
35 }
36
37 public void reset() {
38 window.clear();
39 sum = 0.0;
40 }
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Keeping a running sum turns each average update into constant-time work instead of re-summing the window.
- 2A bounded deque models a sliding window cleanly: append at one end, evict at the other.
- 3Guard edge cases explicitly — reject bad sizes early and return NaN when there's no data to average.
Related explainers
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
java
@GetMapping("/files/{id}") public ResponseEntity<StreamingResponseBody> download( @PathVariable String id, @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader) throws IOException {
HTTP range requests in Spring
http-range
streaming
file-io
Advanced
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-rolling-average-over-a-sliding-window-explained-java-dcc5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.