Created
January 10, 2024 14:30
-
-
Save ribomation/2e824e38c3333e8a2fd3fa9e3e3cd42d to your computer and use it in GitHub Desktop.
1BRC - Baseline solution
This file contains 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
package ribomation; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.util.Locale; | |
import java.util.stream.Collector; | |
import java.util.stream.Collectors; | |
public class CalculateAverage { | |
static final String INPUT_FILE = "./measurements.txt"; | |
public static void main(String[] args) throws IOException { | |
var collector = Collector.of( | |
Aggregation::new, | |
Aggregation::update, | |
Aggregation::combine, | |
Result::create, | |
Collector.Characteristics.UNORDERED | |
); | |
var startTime = System.nanoTime(); | |
try (var lines = Files.lines(Path.of(INPUT_FILE))) { | |
lines | |
.map(Measurement::create) | |
.collect(Collectors.groupingBy(m -> m.station, collector)) | |
.forEach((station, result) -> System.out.printf("%s: %s%n", station, result)); | |
} | |
var endTime = System.nanoTime(); | |
System.out.printf(Locale.ENGLISH, "----%nElapsed time: %.3f secs (%,d records)%n", | |
(endTime - startTime) * 1E-9, Measurement.count); | |
} | |
record Measurement(String station, double temperature) { | |
static int count = 0; | |
Measurement {++count;} | |
Measurement(String[] parts) { | |
this(parts[0], Double.parseDouble(parts[1])); | |
} | |
static Measurement create(String csv) { | |
return new Measurement(csv.split(";")); | |
} | |
} | |
record Result(int count, double mean, double min, double max) { | |
static Result create(Aggregation a) { | |
return new Result(a.count, a.sum / a.count, a.min, a.max); | |
} | |
@Override | |
public String toString() { | |
return String.format(Locale.ENGLISH, "%.1fC, %.1f/%.1f (%d)", mean, min, max, count); | |
} | |
} | |
static class Aggregation { | |
int count = 0; | |
double sum = 0; | |
double min = Double.MAX_VALUE; | |
double max = Double.MIN_VALUE; | |
Aggregation() {} | |
void update(Measurement m) { | |
++count; | |
sum += m.temperature; | |
min = Math.min(min, m.temperature); | |
max = Math.max(max, m.temperature); | |
} | |
static Aggregation combine(Aggregation a, Aggregation b) { | |
var c = new Aggregation(); | |
c.count = a.count + b.count; | |
c.sum = a.sum + b.sum; | |
c.min = Math.min(a.min, b.min); | |
c.max = Math.max(a.max, b.max); | |
return c; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment