- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Java Lambdas from Interfaces to CSV Analysis
A geography data team hands you a raw CSV export of country statistics (code, name, continent, population, area, cities) and asks for a small analyzer: validate and clean rows, filter and sort countries, parse safely into records, then summarize population leaders per continent and group countries by code. You build the analyzer incrementally, one lambda idiom at a time, until it runs as a single reporting tool.
Lab Info
Table of Contents
-
Challenge
Meet the world-population CSV analyzer
The scenario
A geography data team has handed you a raw CSV export of world country statistics:
code,name,continent,population,area,cities. The export is messy — some rows are missing fields, some have non-numeric population values, and the cities column (a;-separated list) is sometimes absent entirely. Your job is to build a small command-line analyzer,world-population-analyzer, that cleans, sorts, parses, and summarizes this data.You will build the analyzer in five stages across this lab, and every stage teaches one idiomatic Java lambda technique you will reuse in the next stage. ## Project layout
All of your work happens under
src/main/java/lab/. You will touch these files, one or two per step:CsvLineHelpers.java— Step 2: raw-line validation lambdasCountryFilters.javaandCountryComparators.java— Step 3: composed predicates and chained comparatorsCountry.javaandCountryParser.java— Step 4: an immutable record and method-reference-based parsingPopulationAnalyzer.java— Step 5: the stream pipeline that produces the final report
Each file starts with working scaffolding and a few
// TODOmarkers. The test suite for each step lives insrc/test/java/lab/StepNTest.javaand runs against exactly the methods you complete. ## Meet the Country domainBy Step 4 you will define
Countryas a Java record:code,name,continent,population,area, andcities(aString[]). Records give you equality,toString, and accessors for free, but an array field is mutable — anyone holding a reference to yourcitiesarray could change it after the record is built. You will fix that with a defensive copy inside the record's compact constructor, one of the small but important habits this lab covers.Until then, Steps 2 and 3 work directly on raw CSV lines and split
String[]fields, so you can practice lambdas and composition before introducing the record type. ## How the stages connect- Step 2 — Validate. Small functional-interface lambdas decide whether a raw line is well-formed, practicing lambda capture.
- Step 3 — Compose.
PredicateandFunctioninstances combine into richer filters; a generic comparator factory chains into multi-level sorts. - Step 4 — Parse. Method references replace hand-written lambdas while you build immutable
Countryrecords, including a fix for an ambiguous constructor call. - Step 5 — Report. Streams and collectors turn a
List<Country>into a population-leaders-per-continent and grouped-by-code report.
Run the full suite at any point with
bash runTest.sh 'Step*Test'. Each task's check only inspects the method it targets, so you can work top to bottom without breaking earlier progress. -
Challenge
Build lambda-driven CSV line helpers that safely capture local state
Functional interfaces and lambda capture
CsvLineHelpers.javaholds small, single-purpose lambdas — the Java idiom for "a function stored as a value." APredicate<String>orFunction<String,String>field assigned a lambda literal is exactly the same shape as a one-method interface implemented anonymously, just shorter to write and read.The subtlety to watch for is capture: a lambda can only read local variables that are effectively final (never reassigned after their first assignment). You cannot increment a plain
intcounter from inside a lambda passed toforEach— the compiler rejects it. The fix, which you will use in Task 2.3, is to capture a reference that itself never changes, such as a one-element array, and mutate what it points to instead of reassigning the local. ## Layering a second predicateOnce a line passes basic shape validation, you often need a second, independent check — is the population field actually usable? Rather than growing
isValidLineinto one long condition, idiomatic Java keeps each check as its own smallPredicate, so callers can mix and match them. That also means each predicate needs to handle its own failure mode: parsing a field that might not be numeric means catchingNumberFormatExceptionlocally rather than letting it escape. ## Mutating captured state safelyNow put capture to work for real: counting how many lines survive both checks. A
forEachlambda over aList<String>cannot close over and reassign a localint, but it can mutate the contents of a captured array, since the array reference itself is never reassigned. This wrapper-array trick is the standard workaround whenever a lambda needs to accumulate a result imperatively instead of through a stream collector. -
Challenge
Compose country predicates and derive chained comparators
Predicates as composable values
CountryFilters.javamoves from single checks to combinations. BecausePredicate<T>is an interface with default methodsand,or, andnegate, you can build one predicate out of two without writing a new lambda body —first.and(second)reads like the boolean logic it performs, and it short-circuits exactly like&&would. The first building block you need is a predicate keyed on one field, ready to be reused and combined. ## Combining predicates instead of duplicating logicFunction<T, R>composes the same way.f.andThen(g)runsfand passes its result tog, andg.compose(f)builds the same chain from the other end. That lets you assemble "read the population column, trim it, parse it" from three tiny functions. WithisContinentin hand, a filter for "this continent, above this population" should not re-derive the continent comparison — it should reuse the existing predicate and.and()it with a check built on that composed function. This is the composition habit that keeps filter logic from sprawling as the analyzer grows more criteria. ## A generic comparator factoryIn
CountryComparators.javayou write a genericbyKeyfactory: given anyFunction<Country, T>key extractor whoseTisComparable, it returns aComparator<Country>that compares on that key. Because it is generic, the same factory builds a comparator on continent, on population, or on any other field, without writing a newComparatorclass each time. The real power shows up when you chain results with.thenComparing(...)— the first comparator decides the primary order, and later ones only get consulted to break ties, which is exactly how a continent-then-population report should read. -
Challenge
Parse CSV rows into defensively-copied records with method references
Records and defensive copying
Country.javadefines the record you will parse rows into. Records generate a canonical constructor automatically, but you can intercept it with a compact constructor — the block that runs before fields are assigned, letting you validate or transform incoming parameters. For an array field likecities, that is where you defend against aliasing: store a clone of the caller's array, not the array itself, so nothing outside the record can mutate its state after construction. ## Method references and an overload trapCountryParser.javareplaces hand-written lambdas with method references wherever a lambda would just forward its argument to an existing method —Long::parseLonginstead ofs -> Long.parseLong(s), for instance. ButCountry(deliberately, for this lab) has two six-argument constructors, one takingString[] citiesand one takingList<String> cities. Passing a barenullfor that argument is ambiguous — the compiler cannot tell which constructor you mean — and the code will not compile until you replace thenullwith something concretely typed, such as an empty array. ## From lines to recordsWith field-level parsing solved, turning a batch of raw lines into
Countryrecords is a filter-then-map stream: reuseCsvLineHelpers::isValidLineas a method reference so validation logic is not duplicated, split each surviving line, and hand the fields toparseFields. Collecting withCollectors.toCollection(ArrayList::new), a constructor reference, gives you a concrete, mutableList<Country>that Step 5 can sort in place. -
Challenge
Stream the analysis and assemble the final report
Grouping and reducing with collectors
PopulationAnalyzer.javais where streams and collectors take over.Collectors.groupingBybuckets a stream by a key function, and its downstream collector decides what happens inside each bucket. PairinggroupingBywithCollectors.maxBypicks the single largest element per group — butmaxByitself returns anOptional(a group could theoretically be empty), so you unwrap it withCollectors.collectingAndThen(..., Optional::get)to get a plain value per key.Collectors.toMapreaches the same result another way: it maps each element straight to a key and value, and calls a merge function such asBinaryOperator.maxBywhenever two elements land on the same key. ## Grouping without reducingNot every grouping needs a reduction. Sometimes the report just needs every member of a bucket, in which case
groupingBy's default downstream collector — which gathers matches into aListic — is exactly what you want, with no second collector argument required. ## Assembling the pipelineEverything you have built is a piece of one pipeline:
CountryParser.parseLinesturns raw lines into records,CountryComparators.byContinentThenPopulationDescendingorders them, and the two grouping methods above summarize them.generateReportis the single entry point that calls all of it in sequence and renders the result as one report string — the moment where every earlier step's work becomes visible at once. -
Challenge
Watch the analyzer clean and summarize country data
Every task is done and graded. Now run the pieces together as one program and watch your code turn raw CSV lines into a report. You will run the analyzer, feed it a bad row and a new country, and rerun the suite.
See the report your code builds
Open the Terminal tab and run:
bash runApp.shYou should see three continent leaders, then one line per code initial:
Continent leader: Europe - Germany (83000000) Continent leader: North America - United States (331000000) Continent leader: South America - Brazil (213000000) Code group A: Argentina Code group B: Brazil ...Each leader comes from your
continentPopulationLeaderscollector in Task 5.1, and eachCode groupline comes from yourgroupByCodeInitialin Task 5.2. The rows were parsed by your method references from Task 4.3, and the sort order comes from your comparator chain in Task 3.3. ### Feed it a bad row and a bigger countryOpen
Main.javain the editor. InsampleData(), find the last row:"FRA,France,Europe,67000000,551000,Paris;Lyon"Replace it with these three rows:
"FRA,France,Europe,67000000,551000,Paris;Lyon", "RUS,Russia,Europe,144000000,17098000,Moscow;Saint Petersburg", "BAD,Not enough fields"Run the
bash runApp.shcommand again. Two things change:- The Europe leader is now
Russia (144000000), and a newCode group R: Russialine appears. Your collectors recomputed the report from the new data. BADappears nowhere in the output. That row has 3 fields instead of 6, so yourisValidLinecheck from Task 2.1 drops it before parsing. NoCode group Bline appears for it, and nothing crashes.
When you are done, put the original
FRArow back.Congratulations on completing the lab!
- The Europe leader is now
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.