Tech Interview RoomStudy guides

Java 17

Java 17: Use records for value objects and composite keys. Compare POJO, string keys, nested maps and records.

Intermediate · 2 min read · Lesson 1 of 8 in Java 17

Problem

Count orders per customer and month (a composite key), and model Money as an immutable value object that validates itself. Records (final in Java 16, part of the Java 17 LTS) target exactly this.

java
import java.time.LocalDate;

final class Purchase {
    final String customerId;
    final LocalDate date;
    Purchase(String customerId, LocalDate date) { this.customerId = customerId; this.date = date; }
}

Approach 1: Hand-written key class (Java 8 POJO)

Correct, but around 30 lines of boilerplate that must be kept in sync: forget a field in equals or hashCode and grouping silently breaks.

java
import java.time.YearMonth;
import java.util.Objects;

final class CustomerMonthPojo {
    private final String customerId;
    private final YearMonth month;

    CustomerMonthPojo(String customerId, YearMonth month) { this.customerId = customerId; this.month = month; }
    String customerId() { return customerId; }
    YearMonth month() { return month; }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof CustomerMonthPojo)) return false;
        CustomerMonthPojo other = (CustomerMonthPojo) o;
        return customerId.equals(other.customerId) && month.equals(other.month);
    }
    @Override public int hashCode() { return Objects.hash(customerId, month); }
    @Override public String toString() { return customerId + "@" + month; }
}

Approach 2: String concatenation key (quick hack)

customerId + "|" + month works until an id contains the separator, and every consumer has to parse the string back. Avoid in real code.

Approach 3: Nested maps

Map<String, Map<YearMonth, Long>> avoids a key class but makes every lookup and iteration two-level and awkward.

Approach 4: A record key (Java 16+), even declared locally inside the method

One line gives final fields, a canonical constructor, accessors, and correct equals, hashCode and toString.

java
import java.time.YearMonth;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

class PurchaseStats {
    static Map<CustomerMonthPojo, Long> withPojo(List<Purchase> purchases) {
        return purchases.stream().collect(Collectors.groupingBy(
            p -> new CustomerMonthPojo(p.customerId, YearMonth.from(p.date)), Collectors.counting()));
    }

    static Map<String, Long> withStringKey(List<Purchase> purchases) {
        return purchases.stream().collect(Collectors.groupingBy(
            p -> p.customerId + "|" + YearMonth.from(p.date), TreeMap::new, Collectors.counting()));
    }

    static Map<String, Map<YearMonth, Long>> withNestedMaps(List<Purchase> purchases) {
        return purchases.stream().collect(Collectors.groupingBy(p -> p.customerId, TreeMap::new,
            Collectors.groupingBy(p -> YearMonth.from(p.date), TreeMap::new, Collectors.counting())));
    }

    record CustomerMonth(String customerId, YearMonth month) {}

    static Map<CustomerMonth, Long> withRecord(List<Purchase> purchases) {
        return purchases.stream().collect(Collectors.groupingBy(
            p -> new CustomerMonth(p.customerId, YearMonth.from(p.date)), Collectors.counting()));
    }
}

Records as validated value objects

A compact constructor validates and normalises before fields are assigned. Records are shallowly immutable, so copy mutable components.

java
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

record Money(BigDecimal amount, String currency) {
    Money {
        Objects.requireNonNull(amount, "amount");
        if (amount.signum() < 0) throw new IllegalArgumentException("negative amount: " + amount);
        if (currency == null || !currency.matches("[A-Z]{3}")) throw new IllegalArgumentException("bad currency: " + currency);
        amount = amount.setScale(2, java.math.RoundingMode.HALF_EVEN);   // normalise so 5 and 5.00 are equal
    }
    Money plus(Money other) {
        if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
        return new Money(amount.add(other.amount), currency);
    }
    static Money of(String amount, String currency) { return new Money(new BigDecimal(amount), currency); }
}

record Basket(String id, List<String> skus) {
    Basket { skus = List.copyOf(skus); }     // defensive, unmodifiable copy
}

class RecordDemo {
    public static void main(String[] args) {
        List<Purchase> ps = List.of(
            new Purchase("c1", java.time.LocalDate.of(2026, 10, 3)), new Purchase("c1", java.time.LocalDate.of(2026, 10, 20)),
            new Purchase("c1", java.time.LocalDate.of(2026, 11, 1)), new Purchase("c2", java.time.LocalDate.of(2026, 10, 9)));
        System.out.println(PurchaseStats.withStringKey(ps));        // {c1|2026-10=2, c1|2026-11=1, c2|2026-10=1}
        System.out.println(PurchaseStats.withNestedMaps(ps));       // {c1={2026-10=2, 2026-11=1}, c2={2026-10=1}}
        System.out.println(PurchaseStats.withRecord(ps).get(new PurchaseStats.CustomerMonth("c1", java.time.YearMonth.of(2026, 10))));  // 2
        System.out.println(PurchaseStats.withPojo(ps).size() == PurchaseStats.withRecord(ps).size());     // true
        System.out.println(Money.of("5", "INR").equals(Money.of("5.00", "INR")));                          // true
        System.out.println(Money.of("10.50", "INR").plus(Money.of("2.25", "INR")));                        // Money[amount=12.75, currency=INR]
        try { Money.of("-1", "INR"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
        java.util.ArrayList<String> skus = new java.util.ArrayList<>(List.of("a"));
        Basket b = new Basket("b1", skus);
        skus.add("b");
        System.out.println(b.skus());                                                                      // [a]
    }
}

Feasible → optimal

String keys work but are fragile; nested maps work but are clumsy; a hand-written POJO is correct but verbose and error-prone. A record is the optimal modern answer: same performance as the POJO, no boilerplate, and correct by construction.

Follow-up questions interviewers ask

Try answering each one before you open it.

Can a record be a JPA entity?

Not well. JPA needs a no-arg constructor, mutable (non-final) fields for dirty checking, and proxies by subclassing, which final records forbid. Use records for DTOs, projections (select new com.x.OrderView(...) or Spring Data interface/record projections), request and response bodies, events and value objects (@Embeddable records are supported since Hibernate 6.2).

What can and can't you add to a record?

You can add static fields and methods, instance methods, nested types, extra constructors that delegate to the canonical one, and implement interfaces. You cannot add instance fields beyond the components, extend another class, or make components non-final. Accessors are amount(), not getAmount(), which matters for some older frameworks (Jackson supports records since 2.12).