On this page
Tutorial: Stream Pipelines & File Processing
Prev: Virtual Threads & HTTP Client | Up: Tutorials | Next: Third-Party Libraries
Rel: java.nio & java.io, java.util.stream, try-with-resources, Lambdas, Streams & Functional Interfaces
Ref: Java 21 API — Files , Java 21 API — Collectors
Tags: #public #java #tutorial #streams #nio #tier/core
Goal
Stream a large CSV or log file lazily with Files.lines(Path), parse structured records, aggregate metrics with Collectors, and write a summary report—without loading the entire file into memory.
Run It Directly
Save as LogSummaryDemo.java and run with OpenJDK 21+:
java LogSummaryDemo.java
Complete Pure-JDK Example
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LogSummaryDemo {
record LogEntry(String level, String service, int latencyMs) {}
static Optional<LogEntry> parseLine(String line) {
String[] parts = line.split(",");
if (parts.length != 3) return Optional.empty();
try {
return Optional.of(new LogEntry(
parts[0].trim(),
parts[1].trim(),
Integer.parseInt(parts[2].trim())
));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static void main(String[] args) throws IOException {
Path tempLog = Files.createTempFile("sample-log-", ".csv");
try {
Files.writeString(tempLog, """
INFO,auth,18
WARN,billing,240
ERROR,billing,510
INFO,auth,22
ERROR,search,320
bad,line
""", StandardCharsets.UTF_8);
// Files.lines() returns a Stream backed by an OS file handle: ALWAYS close it!
try (Stream<String> lines = Files.lines(tempLog, StandardCharsets.UTF_8)) {
Map<String, Double> avgLatencyByService = lines
.map(LogSummaryDemo::parseLine)
.flatMap(Optional::stream)
.collect(Collectors.groupingBy(
LogEntry::service,
Collectors.averagingInt(LogEntry::latencyMs)
));
List<Map.Entry<String, Double>> sorted = avgLatencyByService.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue(Comparator.reverseOrder()))
.toList();
System.out.println("Average latency by service:");
for (var entry : sorted) {
System.out.printf(" %-10s %.1f ms%n", entry.getKey(), entry.getValue());
}
}
} finally {
Files.deleteIfExists(tempLog);
}
}
}
Key Takeaways
- Close I/O-backed streams: Unlike collection streams,
Files.lines()andFiles.walk()hold open file descriptors and must be wrapped intry-with-resources. Optional::streaminflatMap: Cleanly drops malformed lines withoutnullchecks or throwing mid-stream.- Explicit UTF-8: Passing
StandardCharsets.UTF_8(the default since Java 18, JEP 400 ) documents intent clearly across environments.
Linked from
Related notes
- tuts/java/language_and_oop/lambdas_streams_and_functional_interfaces Linked here; links to this page; shared tags: #java, #streams, #tier
- tuts/java/tutorials/virtual_threads_and_http_client Linked here; links to this page; shared tags: #java, #tier, #tutorial
- tuts/java/tutorials Linked here; links to this page; shared tags: #java
- tuts/java/builtins/try_with_resources Linked here; shared tags: #java, #tier
- tuts/java/stdlib/java_nio_and_io Linked here; shared tags: #java
- tuts/java/stdlib/java_util_stream Linked here; shared tags: #java
- tuts/third_party Linked here
- tuts/java/tutorials/modern_data_modeling_records_and_sealed shared tags: #java, #tier, #tutorial
- tuts/cpp/tutorials/jthread_work_queue_and_atomics shared tags: #tier, #tutorial
- tuts/cpp/tutorials/raii_and_rule_of_zero_resource_wrapper shared tags: #tier, #tutorial