On this page
  1. Tutorial: Stream Pipelines & File Processing
  2. Goal
  3. Run It Directly
  4. Complete Pure-JDK Example
  5. Key Takeaways

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

Linked from

Related notes