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 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 platform
Lab Info
Level
Intermediate
Last updated
Dec 01, 2026
Duration
1h 0m

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

    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 lambdas
    • CountryFilters.java and CountryComparators.java — Step 3: composed predicates and chained comparators
    • Country.java and CountryParser.java — Step 4: an immutable record and method-reference-based parsing
    • PopulationAnalyzer.java — Step 5: the stream pipeline that produces the final report

    Each file starts with working scaffolding and a few // TODO markers. The test suite for each step lives in src/test/java/lab/StepNTest.java and runs against exactly the methods you complete. ## Meet the Country domain

    By Step 4 you will define Country as a Java record: code, name, continent, population, area, and cities (a String[]). Records give you equality, toString, and accessors for free, but an array field is mutable — anyone holding a reference to your cities array 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

    1. Step 2 — Validate. Small functional-interface lambdas decide whether a raw line is well-formed, practicing lambda capture.
    2. Step 3 — Compose. Predicate and Function instances combine into richer filters; a generic comparator factory chains into multi-level sorts.
    3. Step 4 — Parse. Method references replace hand-written lambdas while you build immutable Country records, including a fix for an ambiguous constructor call.
    4. 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.

  2. Challenge

    Build lambda-driven CSV line helpers that safely capture local state

    Functional interfaces and lambda capture

    CsvLineHelpers.java holds small, single-purpose lambdas — the Java idiom for "a function stored as a value." A Predicate<String> or Function<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 int counter from inside a lambda passed to forEach — 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 predicate

    Once a line passes basic shape validation, you often need a second, independent check — is the population field actually usable? Rather than growing isValidLine into one long condition, idiomatic Java keeps each check as its own small Predicate, 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 catching NumberFormatException locally rather than letting it escape. ## Mutating captured state safely

    Now put capture to work for real: counting how many lines survive both checks. A forEach lambda over a List<String> cannot close over and reassign a local int, 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.

  3. Challenge

    Compose country predicates and derive chained comparators

    Predicates as composable values

    CountryFilters.java moves from single checks to combinations. Because Predicate<T> is an interface with default methods and, or, and negate, 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 logic

    Function<T, R> composes the same way. f.andThen(g) runs f and passes its result to g, and g.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. With isContinent in 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 factory

    In CountryComparators.java you write a generic byKey factory: given any Function<Country, T> key extractor whose T is Comparable, it returns a Comparator<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 new Comparator class 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.

  4. Challenge

    Parse CSV rows into defensively-copied records with method references

    Records and defensive copying

    Country.java defines 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 like cities, 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 trap

    CountryParser.java replaces hand-written lambdas with method references wherever a lambda would just forward its argument to an existing method — Long::parseLong instead of s -> Long.parseLong(s), for instance. But Country (deliberately, for this lab) has two six-argument constructors, one taking String[] cities and one taking List<String> cities. Passing a bare null for that argument is ambiguous — the compiler cannot tell which constructor you mean — and the code will not compile until you replace the null with something concretely typed, such as an empty array. ## From lines to records

    With field-level parsing solved, turning a batch of raw lines into Country records is a filter-then-map stream: reuse CsvLineHelpers::isValidLine as a method reference so validation logic is not duplicated, split each surviving line, and hand the fields to parseFields. Collecting with Collectors.toCollection(ArrayList::new), a constructor reference, gives you a concrete, mutable List<Country> that Step 5 can sort in place.

  5. Challenge

    Stream the analysis and assemble the final report

    Grouping and reducing with collectors

    PopulationAnalyzer.java is where streams and collectors take over. Collectors.groupingBy buckets a stream by a key function, and its downstream collector decides what happens inside each bucket. Pairing groupingBy with Collectors.maxBy picks the single largest element per group — but maxBy itself returns an Optional (a group could theoretically be empty), so you unwrap it with Collectors.collectingAndThen(..., Optional::get) to get a plain value per key. Collectors.toMap reaches the same result another way: it maps each element straight to a key and value, and calls a merge function such as BinaryOperator.maxBy whenever two elements land on the same key. ## Grouping without reducing

    Not 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 a Listic — is exactly what you want, with no second collector argument required. ## Assembling the pipeline

    Everything you have built is a piece of one pipeline: CountryParser.parseLines turns raw lines into records, CountryComparators.byContinentThenPopulationDescending orders them, and the two grouping methods above summarize them. generateReport is 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.

  6. 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.sh
    

    You 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 continentPopulationLeaders collector in Task 5.1, and each Code group line comes from your groupByCodeInitial in 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 country

    Open Main.java in the editor. In sampleData(), 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.sh command again. Two things change:

    • The Europe leader is now Russia (144000000), and a new Code group R: Russia line appears. Your collectors recomputed the report from the new data.
    • BAD appears nowhere in the output. That row has 3 fields instead of 6, so your isValidLine check from Task 2.1 drops it before parsing. No Code group B line appears for it, and nothing crashes.

    When you are done, put the original FRA row back.

    Congratulations on completing the lab!

About the author

Jeff Hopper is a polyglot solution developer with over 20 years of experience across several business domains. He has enjoyed many of those years focusing on the .Net stack.

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