Skip to content

Instantly share code, notes, and snippets.

@rokon12
Created June 29, 2025 02:17
Show Gist options
  • Save rokon12/af22c7edaba26110cd1e012b246a3d8d to your computer and use it in GitHub Desktop.
Save rokon12/af22c7edaba26110cd1e012b246a3d8d to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - Statistics.java
class Statistics {
int count = 0;
int sum = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
Statistics add(Integer value) {
count++; // 1️⃣ Track how many elements
sum += value; // 2️⃣ Running total
min = Math.min(min, value); // 3️⃣ Track minimum
max = Math.max(max, value); // 4️⃣ Track maximum
return this; // 5️⃣ Return self for chaining
}
double getAverage() {
return count == 0 ? 0 : (double) sum / count;
}
}
Statistics stats = values.stream()
.gather(Gatherers.fold(
Statistics::new, // 1️⃣ Create fresh Statistics object
Statistics::add // 2️⃣ Add each element to our statistics
))
.findFirst() // 3️⃣ Fold returns a single-element stream
.orElse(new Statistics());
System.out.printf("Count: %d, Sum: %d, Avg: %.2f, Min: %d, Max: %d%n",
stats.count, stats.sum, stats.getAverage(), stats.min, stats.max);
// Output: Count: 9, Sum: 45, Avg: 5.00, Min: 1, Max: 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment