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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 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.