- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
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 Info
Table of Contents
-
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,engineTempCthroughout 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 givenThe starter project already defines two types you'll use everywhere: the
SensorReadingrecord (vehicleId,timestamp,speedKph,engineTempC) andReadingParseException, 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 intoSensorReadingvalues, streaming them from files and from synthetic generators, detecting anomalies as they flow past, and reducing large collections down to dashboard-ready summaries. ## Project layoutAll of your edits live under
src/main/java/lab/. Each step's tests live in a matchingsrc/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 undersolution/. ## Where this goesStep 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
Gathererthat 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. -
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 validatedSensorReadingor fail loudly with aReadingParseExceptionthat 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 chainWith
parseLinein hand, the next job is a stream pipeline that filters and converts readings. It's the bread-and-butterfilter/mapchain, 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 inputStream.reduceand friends have a problem: what's the average of zero readings?mapToDouble(...).average()sidesteps that by returningOptionalDoubleinstead 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 anOptional, pushing the "what if there's nothing" decision to the caller. -
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 lazyStream<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 atry-with-resources block guarantees gets closed, even when parsing throws partway through. ## Generating data without a fileEngineers 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 withlimit, it becomes a bounded, repeatable generator. ## Stopping before you've looked at everythingA lazily-generated or file-backed stream can be enormous, so scanning it end to end just to find the first dangerous reading wastes work.
filterfollowed byfindFirstshort-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. -
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.
filterandmaponly ever look at one element at a time, so spotting a spike needs a stream operation with memory: aGatherer. AGatherercarries mutable state across calls to its integrator, letting you compare each element to the last one you saw. ## Why this gatherer has no combinerParallel 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.ofcombiner only merges state after each partition has already finished, which is too late to catch a spike that straddles two partitions.Gatherer.ofSequential, whichbuildSpikeGathereralready 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. -
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.groupingBysplits a stream into buckets keyed by a classifier (here,vehicleId), and a downstream collector likesummarizingDoublereduces each bucket in the same single pass, so you never iterate the readings more than once to get there. ## Two reductions, one traversalThe fleet-wide report needs both a count and an average, which normally means two separate reductions over the same data.
Collectors.teeingruns two downstream collectors over the same stream in a single pass and merges their results with a function you supply (here, into oneFleetSummaryrecord). ## Reporting every bad line, not just the firstThe 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
ReadingParseExceptionper line instead of per file, and accumulating both successes and failures as you go. -
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.csvis 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.Mainreads it and runs it through every method you wrote.Open the Terminal tab and run:
bash runApp.shThe 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
readFilefrom 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. YourLineAwareParserfrom Task 5.3 reads the same 12 lines and keeps going:9 readings, 3 malformed lines, thenline 4(a missing field),line 6(a speed offast) andline 9(a timestamp with no date). Each message is theReadingParseExceptionyour 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.0to52,0and save. The extra comma splits that line into five fields instead of four. Run the app again:bash runApp.shCompare 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 linesbecomes8 readings, 4 malformed lines. Your typo is listed first asline 1, and lines 4, 6 and 9 are still reported below it. - van-1's average speed:
56.7 kphbecomes59.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,0back to52.0and save before you continue. ### Fleet reports from the good readingsOnly the 9 readings that parsed reach the reports. The per-vehicle averages
van-1: 56.7 kph,van-2: 64.0 kphandvan-3: 48.5 kphcome from the singlegroupingByyou wrote in Task 5.1, with no loop per vehicle. The lineFleet summary in one pass (Task 5.2): min 80.0 C, max 104.0 C, average 86.3 Cis three results from one traversal, because your nestedteeingcollectors run side by side. Your Task 2.3 average agrees at86.3 C, and whenMainasks it for the average of no readings at all, it printsOptional.emptyinstead of throwing. ### Gatherers that remember, and one that stops earlyThe anomalies section lists two jumps:
van-1 ... 91.0 C(up from 83.0) andvan-2 ... 104.0 C(up from 85.5). Your Task 4.1 gatherer caught them by carrying the previous temperature in its state.Mainfeeds each van's readings through your Task 4.3detectSpikesInParallel, so even on a parallel stream every reading is compared with the right predecessor.The next line says
pulled 8 of 9 readings.Maincounts each reading as it leaves the source. Once your Task 4.2 integrator returnedfalseat 104.0 C, the stream never asked for van-3's last reading. The last line is the same idea from Task 3.3:findFirstacross the file and the 20 synthetic readings from Task 3.1 stops atvan-1 ... 91.0 Cin 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!
- Strict read: it stopped at line 4 before. Now it stops at line 1, with
About the author
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.