Brainbotox · Lessons · Exams

Java Intermediate for Confirmed Developers: Streams, Generics

by lazizanie · Programming · Java · English

Intermediate Java for confirmed developers: generics and collections, lambdas and Optional, the Streams API, records and sealed classes, concurrency basics, testing with JUnit.

Study this lesson with its quizzes on Brainbotox →

Java generics and collections in depth

Generics give compile-time type safety to classes and methods, but the type arguments are erased at run time. Choosing the right collection and writing correct equals and hashCode are core intermediate skills.

Generic methods and bounded types

static <T extends Comparable<T>> T max(List<T> items) {
    T best = items.get(0);
    for (T it : items) if (it.compareTo(best) > 0) best = it;
    return best;
}

Type erasure

The compiler checks generic types, then removes them. At run time a List<String> and a List<Integer> are the same class. Consequences: no new T(), no instanceof List<String>, no generic arrays, and no primitives as type arguments.

Wildcards and PECS

double sum(List<? extends Number> src) { ... }   // read from it
void fill(List<? super Integer> dst) { dst.add(1); } // write into it
PECS: Producer Extends, Consumer Super. Generics are invariant: a List<Integer> is not a List<Number>.

Choosing a collection

TypeOrderTypical cost
ArrayListInsertion, indexedget O(1), insert in middle O(n)
LinkedListInsertionget O(n); rarely the best choice
HashMap / HashSetNoneO(1) on average
LinkedHashMapInsertion orderO(1) on average
TreeMap / TreeSetSorted by keyO(log n)
ArrayDequeQueue or stackO(1) at both ends

equals and hashCode

If two objects are equal according to equals(), they must return the same hashCode(). Override both together, or objects get lost in HashMap and HashSet. Do not mutate a field used in hashCode while the object is a map key.

Ordering and immutability

people.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));
List<String> fixed = List.of("a", "b");    // immutable: add() throws

Comparable defines the natural order inside the class (compareTo). A Comparator defines an external order.

Check yourself

  1. What is type erasure?
  2. Which parameter type accepts a List<Integer> and a List<Double> for reading numbers?
  3. List<Integer> is a subtype of List<Number>.
  4. Which map keeps its keys sorted?
  5. What is the contract between equals and hashCode?
  6. What happens when you call add on a list created by List.of(...)?

Take the quiz on Brainbotox

Java lambdas, functional interfaces and Optional

A lambda expression is a short way to implement a functional interface, which is an interface with exactly one abstract method. It lets you pass behaviour as an argument.

Lambdas

Comparator<String> byLength = (a, b) -> a.length() - b.length();
Runnable task = () -> System.out.println("run");
Function<Integer, Integer> square = x -> x * x;

The standard functional interfaces

InterfaceMethodShape
Function<T, R>applyT to R
Predicate<T>testT to boolean
Consumer<T>acceptT to nothing
Supplier<T>getnothing to T
UnaryOperator<T>, BinaryOperator<T>applyT to T; (T, T) to T

Method references

names.forEach(System.out::println);          // instance method of an object
names.stream().map(String::length);          // instance method of the type
Supplier<List<String>> maker = ArrayList::new; // constructor

Capturing variables

A lambda can use local variables of the enclosing method only if they are effectively final: never reassigned after initialisation.

Optional

Optional<User> user = repo.findById(id);
String name = user.map(User::getName).orElse("unknown");
User u = user.orElseThrow(() -> new NotFoundException(id));
user.ifPresent(x -> send(x));
  • Optional is a return type that says "there may be no result", in place of null.
  • Optional.of(x) throws on null; use Optional.ofNullable(x) when x may be null.
  • Calling get() on an empty Optional throws NoSuchElementException.
  • Do not use it for fields or method parameters.
Mark your own single-method interfaces with @FunctionalInterface: the compiler then rejects a second abstract method.

Check yourself

  1. What is a functional interface?
  2. Which interface represents a function from T to boolean?
  3. Which local variables can a lambda use?
  4. What does String::length represent?
  5. What does Optional.of(null) do?
  6. What is the main purpose of Optional?

Take the quiz on Brainbotox

The Java Streams API

A stream is a pipeline that processes a sequence of elements declaratively: a source, zero or more lazy intermediate operations, and one terminal operation that produces the result.

A pipeline

List<String> names = people.stream()                 // source
    .filter(p -> p.getAge() >= 18)                    // intermediate
    .sorted(Comparator.comparing(Person::getName))    // intermediate
    .map(Person::getName)                             // intermediate
    .toList();                                        // terminal
Intermediate (lazy)Terminal (runs the pipeline)
filter, map, flatMapcollect, toList, forEach
sorted, distinctcount, reduce, sum
limit, skip, peekfindFirst, anyMatch, allMatch
Nothing happens until the terminal operation is called. A stream can be consumed only once: reusing it throws IllegalStateException. A stream does not modify its source.

Collectors

Map<String, List<Person>> byCity =
    people.stream().collect(Collectors.groupingBy(Person::getCity));
Map<String, Long> countByCity =
    people.stream().collect(Collectors.groupingBy(Person::getCity, Collectors.counting()));
String csv = names.stream().collect(Collectors.joining(", "));

flatMap and reduce

List<String> allTags = posts.stream()
    .flatMap(p -> p.getTags().stream())    // stream of lists to one stream
    .distinct().toList();
int total = numbers.stream().reduce(0, Integer::sum);

Primitive streams

IntStream, LongStream and DoubleStream avoid boxing: people.stream().mapToInt(Person::getAge).average().

Parallel streams

parallelStream() splits work over the common ForkJoinPool. It helps only for large, CPU-heavy, independent work. It is harmful with blocking I/O, small collections or lambdas that modify shared state.
Keep lambdas in streams free of side effects. To build a result, use a collector, not forEach adding to an outside list.

Check yourself

  1. When do the intermediate operations of a stream execute?
  2. What happens if you use a stream a second time?
  3. Which operation turns a stream of lists into one stream of their elements?
  4. Which collector groups elements into a Map by a key?
  5. Which of these is a terminal operation?
  6. When is a parallel stream a poor choice?

Take the quiz on Brainbotox

Modern Java: records, sealed classes and pattern matching

Since Java 14 the language has added records for immutable data, sealed types for closed hierarchies, and pattern matching to test and destructure values. Together they replace much boilerplate.

Records

public record Point(int x, int y) {
    public Point {                         // compact constructor: validation
        if (x < 0) throw new IllegalArgumentException("x");
    }
    double distance() { return Math.sqrt(x * x + y * y); }
}
Point p = new Point(3, 4);
p.x();                                     // accessor, not getX()
p.equals(new Point(3, 4));                 // true
A record is a final class with private final fields. The compiler generates the constructor, accessors, equals, hashCode and toString. Records cannot extend a class but can implement interfaces.

Sealed classes and interfaces

public sealed interface Shape permits Circle, Square { }
public record Circle(double r) implements Shape { }
public record Square(double side) implements Shape { }

Only the listed types may implement Shape, so the compiler knows every possible case.

Pattern matching

if (obj instanceof String s && s.length() > 3) {     // test and cast
    System.out.println(s.toUpperCase());
}
double area = switch (shape) {                        // Java 21
    case Circle c -> Math.PI * c.r() * c.r();
    case Square(double side) -> side * side;          // record pattern
};                                                    // no default: sealed

With a sealed type, the switch is checked for exhaustiveness: adding a new shape makes this code fail to compile until it is handled.

Other additions

FeatureExample
Text blocks""" multi-line strings """
varLocal variable type inference
Enhanced enumsEnums with fields, constructors and methods
Helpful NullPointerException messagesThey name the null variable

Check yourself

  1. What does the compiler generate for a record?
  2. How do you read the x component of record Point(int x, int y)?
  3. The fields of a record can be reassigned after construction.
  4. What does a sealed interface with a permits clause do?
  5. What does if (obj instanceof String s) do?
  6. Why can a switch over a sealed type omit default?

Take the quiz on Brainbotox

Java concurrency basics: threads, executors, CompletableFuture

Java runs code concurrently on threads, usually managed by an ExecutorService, and protects shared data with synchronized, atomic classes and concurrent collections.

Threads and executors

Thread t = new Thread(() -> System.out.println("working"));
t.start();                  // start() creates a new thread; run() would not
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> compute());
int result = f.get();       // blocks until done
pool.shutdown();

Creating a thread per task is expensive. A pool reuses a fixed set of threads.

Race conditions

class Counter {
    private int n;
    public synchronized void inc() { n++; }   // one thread at a time
}

n++ is read, add, write. Without synchronisation two threads can lose an update.

ToolGives
synchronizedMutual exclusion and visibility
volatileVisibility of the latest value only; n++ is still not atomic
AtomicIntegerLock-free atomic operations: incrementAndGet()
ConcurrentHashMapA thread-safe map with atomic merge and computeIfAbsent
Deadlock: thread 1 holds lock A and waits for B while thread 2 holds B and waits for A. Always acquire locks in the same order.

CompletableFuture

CompletableFuture<String> user = CompletableFuture.supplyAsync(() -> loadUser(id));
CompletableFuture<Integer> orders = CompletableFuture.supplyAsync(() -> countOrders(id));
String summary = user
    .thenCombine(orders, (u, n) -> u + " has " + n + " orders")
    .exceptionally(ex -> "unavailable")
    .join();

It composes asynchronous steps without blocking between them.

Virtual threads (Java 21)

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    executor.submit(() -> handle(request));
}

Virtual threads are lightweight threads managed by the JVM. An application can run very many of them, which suits code that mostly waits on I/O.

Check yourself

  1. What is the difference between t.start() and t.run()?
  2. Why use a thread pool?
  3. What does volatile guarantee?
  4. Which class gives an atomic counter without locks?
  5. What does Future.get() do?
  6. What are virtual threads best suited for?

Take the quiz on Brainbotox

Java resources, testing with JUnit and build tools

Professional Java code releases resources reliably, designs its exceptions, is covered by automated tests and is built by Maven or Gradle.

Exceptions done well

public class OrderNotFoundException extends RuntimeException {
    public OrderNotFoundException(long id, Throwable cause) {
        super("Order " + id + " not found", cause);    // keep the cause
    }
}
  • Catch the most specific type you can handle. Never leave a catch block empty.
  • When you wrap an exception, pass the original as the cause.
  • Do not use exceptions for normal control flow.

try-with-resources in detail

try (var in = Files.newInputStream(src); var out = Files.newOutputStream(dst)) {
    in.transferTo(out);
}

Any AutoCloseable works. Resources are closed in reverse order. If closing also fails, that exception is attached as a suppressed exception.

Files with NIO

Path path = Path.of("data", "notes.txt");
String text = Files.readString(path);
List<String> lines = Files.readAllLines(path);
Files.writeString(path, "hello");

JUnit 5

class CalculatorTest {
    Calculator calc;
    @BeforeEach
    void setUp() { calc = new Calculator(); }
    @Test
    void addsTwoNumbers() { assertEquals(5, calc.add(2, 3)); }
    @Test
    void rejectsDivisionByZero() {
        assertThrows(ArithmeticException.class, () -> calc.divide(1, 0));
    }
    @ParameterizedTest
    @CsvSource({"1,1,2", "2,3,5"})
    void adds(int a, int b, int expected) { assertEquals(expected, calc.add(a, b)); }
}
A good unit test is fast, independent of other tests, and follows Arrange, Act, Assert. Replace slow collaborators (database, network) with mocks, for example using Mockito.

Maven and Gradle

MavenGradle
Build filepom.xmlbuild.gradle(.kts)
StyleDeclarative XML, fixed lifecycleScript in Groovy or Kotlin
Run testsmvn testgradle test

Both download dependencies (identified by group, artifact and version) and their transitive dependencies. A dependency with test scope is not shipped in the application.

Check yourself

  1. In which order are resources closed in try-with-resources?
  2. Why pass the original exception as the cause when wrapping?
  3. Which JUnit 5 assertion checks that code throws?
  4. What does @BeforeEach do?
  5. What is Maven's build file?
  6. Which interface must a class implement to be used in try-with-resources?

Take the quiz on Brainbotox