← Java

Java · 19 / 24

Generics, collections and streams in a domain task

Group validated costs and return an immutable result structure.

  • Large
  • Advanced
  • 90 min

Prerequisites: Arrays, lists, sets and maps, Interfaces and composition

In this tutorial
  1. Read the domain contract
  2. Start an isolated environment
  3. Verify success and failure
  4. Make a regression visible
  5. Extend the contract
  6. Explain the solution and its limits
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

JDK 21, Maven 3.9 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. JUnit checks grouping, totals, negative amounts and overflow. The solution adds empty inputs and immutability of the outer map. List.copyOf and Map.copyOf protect results from subsequent changes.

A collection defines properties such as ordering and uniqueness. Streams describe processing. The generic helper avoids changing input types through unsafe casts. Amounts are stored in cents and checked addition prevents silent overflow.

Package contents and individual files

01Read the domain contract

Generics retain a collection element type. Stream operations form a pipeline of filtering, mapping and collecting. Intermediate operations execute only when a terminal operation runs. Avoid hidden side effects in map.

src/main/java/tutorial/Ledger.java · javaOpen file
package tutorial;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Ledger {

  public record Entry(String vehicle, long cents) {
    public Entry {
      if (
        vehicle == null || vehicle.isBlank() || cents < 0
      ) throw new IllegalArgumentException("Invalid entry");
    }
  }

  public static <T, K> Map<K, List<T>> group(
    List<T> values,
    Function<T, K> key
  ) {
    var grouped = values.stream().collect(Collectors.groupingBy(key));
    var immutable = new HashMap<K, List<T>>();
    grouped.forEach((k, v) -> immutable.put(k, List.copyOf(v)));
    return Map.copyOf(immutable);
  }

  public static long total(List<Entry> values) {
    return values.stream().mapToLong(Entry::cents).reduce(0, Math::addExact);
  }
}

02Start an isolated environment

Java 21 is the language baseline. Maven resolves dependencies from the POM. Tests use their own data. HTTP tests start a server on a randomly assigned local port.

pom.xml · xmlOpen file
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.1.0</version></parent>
<groupId>learning</groupId><artifactId>tutorial</artifactId><version>1.0</version>
<properties><java.version>21</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

</dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

03Verify success and failure

JUnit checks grouping, totals, negative amounts and overflow. The solution adds empty inputs and immutability of the outer map. List.copyOf and Map.copyOf protect results from subsequent changes.

src/test/java/tutorial/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.util.*;
import org.junit.jupiter.api.Test;

class LessonTest {

  @Test
  void groupsAndTotals() {
    var rows = List.of(
      new Ledger.Entry("car", 100),
      new Ledger.Entry("car", 200),
      new Ledger.Entry("bike", 50)
    );
    var groups = Ledger.group(rows, Ledger.Entry::vehicle);
    assertEquals(300, Ledger.total(groups.get("car")));
    assertEquals(50, Ledger.total(groups.get("bike")));
    assertThrows(UnsupportedOperationException.class, () ->
      groups.get("car").clear()
    );
  }

  @Test
  void invalidAndOverflow() {
    assertThrows(IllegalArgumentException.class, () ->
      new Ledger.Entry("car", -1)
    );
    assertThrows(ArithmeticException.class, () ->
      Ledger.total(
        List.of(
          new Ledger.Entry("car", Long.MAX_VALUE),
          new Ledger.Entry("car", 1)
        )
      )
    );
  }
}

Run / check

mvn test
Expected result

Groups and totals match. Invalid values are rejected. Result collections cannot be modified.

04Make a regression visible

Change a domain expectation and rerun the test. Maven must report failure. A skipped database test is not evidence. Restore the correct expectation afterwards.

05Extend the contract

Verify empty input and immutability of the outer map.

06Explain the solution and its limits

An empty list produces an empty map and a zero total. Map.copyOf protects the mapping and List.copyOf additionally protects its lists. These are separate guarantees. Copy solution/LessonTest.java over the test file and repeat the same verification.

Expected result

All tests pass, including the additional solution expectation.

Your exercise

Verify empty input and immutability of the outer map.

Show the solution and explanation

An empty list produces an empty map and a zero total. Map.copyOf protects the mapping and List.copyOf additionally protects its lists. These are separate guarantees.

solution/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.util.*;
import org.junit.jupiter.api.Test;

class LessonTest {

  @Test
  void emptyAndOuterMap() {
    assertEquals(0, Ledger.total(List.of()));
    assertTrue(
      Ledger.group(List.<Ledger.Entry>of(), Ledger.Entry::vehicle).isEmpty()
    );
    assertThrows(UnsupportedOperationException.class, () ->
      Ledger.group(
        List.of(new Ledger.Entry("car", 1)),
        Ledger.Entry::vehicle
      ).clear()
    );
  }

  @Test
  void groupsAndTotals() {
    var rows = List.of(
      new Ledger.Entry("car", 100),
      new Ledger.Entry("car", 200),
      new Ledger.Entry("bike", 50)
    );
    var groups = Ledger.group(rows, Ledger.Entry::vehicle);
    assertEquals(300, Ledger.total(groups.get("car")));
    assertEquals(50, Ledger.total(groups.get("bike")));
    assertThrows(UnsupportedOperationException.class, () ->
      groups.get("car").clear()
    );
  }

  @Test
  void invalidAndOverflow() {
    assertThrows(IllegalArgumentException.class, () ->
      new Ledger.Entry("car", -1)
    );
    assertThrows(ArithmeticException.class, () ->
      Ledger.total(
        List.of(
          new Ledger.Entry("car", Long.MAX_VALUE),
          new Ledger.Entry("car", 1)
        )
      )
    );
  }
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.