Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

Java Streams Pipelines and Gatherers

Fleet operations engineers need a small analyzer for CSV telemetry logs (vehicleId, timestamp, speedKph, engineTempC) produced by delivery vans. Files sometimes contain malformed lines that must be reported with their line numbers rather than silently dropped or crash the whole run. Engineers also want synthetic test data generated on demand, early detection of dangerous engine-temperature spikes without scanning an entire large file, and per-vehicle plus fleet-wide statistics for a dashboard.

Lab platform
Lab Info
Level
Intermediate
Last updated
Dec 01, 2026
Duration
1h 30m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. Challenge

    Explore the fleet telemetry scenario

    Making sense of noisy fleet telemetry

    Delivery vans across the fleet write CSV log lines of the form vehicleId,timestamp,speedKph,engineTempC throughout the day. Operations engineers pull these files into the analyzer you're building in this lab to answer three questions: which vehicles are speeding, which engines are overheating right now, and which lines in a log are garbage that needs a human to look at. A single malformed line (a missing field, a non-numeric temperature) must never crash the whole run or silently vanish. It has to show up in a report with its line number attached. ## The data you're given

    The starter project already defines two types you'll use everywhere: the SensorReading record (vehicleId, timestamp, speedKph, engineTempC) and ReadingParseException, a checked exception that carries the offending raw line and a human-readable reason. You will not change either type. Instead you'll write the code around them: parsing raw text into SensorReading values, streaming them from files and from synthetic generators, detecting anomalies as they flow past, and reducing large collections down to dashboard-ready summaries. ## Project layout

    All of your edits live under src/main/java/lab/. Each step's tests live in a matching src/test/java/lab/StepNTest.java, already wired against the method signatures the starter declares. Before you write a single line, the project compiles and every later step's tests already exist, just failing. You'll fill in the bodies of methods marked // TODO: Task N.M - ..., one file at a time, without ever touching the test files, pom.xml, or anything under solution/. ## Where this goes

    Step 2 builds the core parsing and transformation pipeline on in-memory data. Step 3 connects that pipeline to real files and synthetic generators, and proves it can stop early instead of scanning everything. Step 4 introduces a custom stateful Gatherer that detects engine-temperature spikes as it scans, including what happens (and what doesn't) when you point it at a parallel stream. Step 5 composes everything into per-vehicle and fleet-wide reports, and rewrites the file parser so it captures every bad line in one pass instead of stopping at the first one.

  2. Challenge

    Build the foundational parsing and transformation pipeline

    Turning raw text into typed readings

    Every pipeline in the analyzer starts from text: a line like V12,1700000000,54.2,88.1. Before any stream operation can filter or aggregate readings, that line has to become a validated SensorReading or fail loudly with a ReadingParseException that names the bad line. This is the one place in the whole codebase where untyped text meets typed data, so get it right here and everything downstream can assume clean input. ## Type-aware operations in the middle of a chain

    With parseLine in hand, the next job is a stream pipeline that filters and converts readings. It's the bread-and-butter filter/map chain, but applied with attention to the units involved. Speeds arrive in kph, and the dashboard wants mph. Mixing up which operation runs first, or converting before filtering, changes both the result and how much work the pipeline does. ## Reducing without crashing on empty input

    Stream.reduce and friends have a problem: what's the average of zero readings? mapToDouble(...).average() sidesteps that by returning OptionalDouble instead of throwing or returning a meaningless default. Any terminal reduction over data that might be empty (and a filtered stream of sensor readings always might be) should return an Optional, pushing the "what if there's nothing" decision to the caller.

  3. Challenge

    Connect the pipeline to generated and file-backed data

    Reading a log file lazily, and closing it properly

    Real logs live on disk and can be large. Files.lines(path) gives you a lazy Stream<String> instead of loading the whole file into memory, but that laziness comes with a catch: the stream holds an open file handle that only a try-with-resources block guarantees gets closed, even when parsing throws partway through. ## Generating data without a file

    Engineers testing the analyzer don't want to hand-craft log files for every scenario. Stream.iterate(seed, next) builds an infinite, lazy sequence where each element is derived from the one before it. That's exactly the shape of a synthetic sensor feed, where the next reading's timestamp and values follow from the last. Paired with limit, it becomes a bounded, repeatable generator. ## Stopping before you've looked at everything

    A lazily-generated or file-backed stream can be enormous, so scanning it end to end just to find the first dangerous reading wastes work. filter followed by findFirst short-circuits: as soon as one element satisfies the predicate, upstream production of further elements stops. That's the difference between a terminal operation that must see every element and one that can stop the moment it's satisfied.

  4. Challenge

    Write a stateful anomaly-detecting gatherer

    Detecting a spike means remembering what came before

    A single reading can't be a "spike" on its own. A spike is a jump relative to the reading before it. filter and map only ever look at one element at a time, so spotting a spike needs a stream operation with memory: a Gatherer. A Gatherer carries mutable state across calls to its integrator, letting you compare each element to the last one you saw. ## Why this gatherer has no combiner

    Parallel streams normally split work across partitions and merge partial results with a combiner. That works when each partition's result is independent of the others. Spike detection isn't independent: it compares each reading to its immediate predecessor, and a partition boundary has no predecessor to compare against. A Gatherer.of combiner only merges state after each partition has already finished, which is too late to catch a spike that straddles two partitions. Gatherer.ofSequential, which buildSpikeGatherer already returns, is exactly how a gatherer tells the stream machinery "don't split my traversal," so calling it from a parallel source is safe by construction, not by accident.

  5. Challenge

    Aggregate fleet reports and capture every parse error

    One pass, grouped by vehicle

    The dashboard wants a summary per vehicle, not one number for the whole fleet. Collectors.groupingBy splits a stream into buckets keyed by a classifier (here, vehicleId), and a downstream collector like summarizingDouble reduces each bucket in the same single pass, so you never iterate the readings more than once to get there. ## Two reductions, one traversal

    The fleet-wide report needs both a count and an average, which normally means two separate reductions over the same data. Collectors.teeing runs two downstream collectors over the same stream in a single pass and merges their results with a function you supply (here, into one FleetSummary record). ## Reporting every bad line, not just the first

    The original parser throws on the first malformed line and stops. Operations engineers need the opposite: every bad line's number and reason, alongside every reading that did parse successfully, from one pass over the file. That means pairing each line with its line number before parsing it, catching ReadingParseException per line instead of per file, and accumulating both successes and failures as you go.

  6. Challenge

    Run the analyzer on a messy log file

    Run the analyzer on a messy log

    Now see the pieces work together on one real file. data/telemetry.csv is a 12-line log from three vans. It hides three broken lines, a temperature spike for two of the vans, and one reading above 100 °C. Main reads it and runs it through every method you wrote.

    Open the Terminal tab and run:

    bash runApp.sh
    

    The output has three sections: parsing, the fleet report, and anomalies. Each line names the task that produced it. ### Every bad line, reported in one pass

    Start with the parsing section. Your strict readFile from Task 3.2 gives up at the first problem: Strict read (Task 3.2) stopped at the first bad line, followed by line 4's text. Your LineAwareParser from Task 5.3 reads the same 12 lines and keeps going: 9 readings, 3 malformed lines, then line 4 (a missing field), line 6 (a speed of fast) and line 9 (a timestamp with no date). Each message is the ReadingParseException your Task 2.1 parser threw, now tagged with the line it came from.

    Watch the parser catch your own typo

    Now break a line yourself. Open the telemetry.csv editor tab. On line 1, change the speed 52.0 to 52,0 and save. The extra comma splits that line into five fields instead of four. Run the app again:

    bash runApp.sh
    

    Compare three lines with your first run:

    • Strict read: it stopped at line 4 before. Now it stops at line 1, with Expected 4 fields but found 5. It gives up at the first bad line, so it never sees the other three.
    • Line-aware parse: 9 readings, 3 malformed lines becomes 8 readings, 4 malformed lines. Your typo is listed first as line 1, and lines 4, 6 and 9 are still reported below it.
    • van-1's average speed: 56.7 kph becomes 59.0 kph. The broken line is left out of the report, so van-1's average is now taken over its two remaining readings.

    Change 52,0 back to 52.0 and save before you continue. ### Fleet reports from the good readings

    Only the 9 readings that parsed reach the reports. The per-vehicle averages van-1: 56.7 kph, van-2: 64.0 kph and van-3: 48.5 kph come from the single groupingBy you wrote in Task 5.1, with no loop per vehicle. The line Fleet summary in one pass (Task 5.2): min 80.0 C, max 104.0 C, average 86.3 C is three results from one traversal, because your nested teeing collectors run side by side. Your Task 2.3 average agrees at 86.3 C, and when Main asks it for the average of no readings at all, it prints Optional.empty instead of throwing. ### Gatherers that remember, and one that stops early

    The anomalies section lists two jumps: van-1 ... 91.0 C (up from 83.0) and van-2 ... 104.0 C (up from 85.5). Your Task 4.1 gatherer caught them by carrying the previous temperature in its state. Main feeds each van's readings through your Task 4.3 detectSpikesInParallel, so even on a parallel stream every reading is compared with the right predecessor.

    The next line says pulled 8 of 9 readings. Main counts each reading as it leaves the source. Once your Task 4.2 integrator returned false at 104.0 C, the stream never asked for van-3's last reading. The last line is the same idea from Task 3.3: findFirst across the file and the 20 synthetic readings from Task 3.1 stops at van-1 ... 91.0 C in the file, so none of the generated readings is ever examined.

    You now have an analyzer that survives bad input, reports every problem by line, and stops reading as soon as it has its answer.

    Congratulations on completing this lab!

About the author

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight