Java Intermediate for Confirmed Developers: Streams, Generics
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 itList<Integer> is not a List<Number>.Choosing a collection
| Type | Order | Typical cost |
|---|---|---|
ArrayList | Insertion, indexed | get O(1), insert in middle O(n) |
LinkedList | Insertion | get O(n); rarely the best choice |
HashMap / HashSet | None | O(1) on average |
LinkedHashMap | Insertion order | O(1) on average |
TreeMap / TreeSet | Sorted by key | O(log n) |
ArrayDeque | Queue or stack | O(1) at both ends |
equals and hashCode
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() throwsComparable defines the natural order inside the class (compareTo). A Comparator defines an external order.
Check yourself
- What is type erasure?
- Which parameter type accepts a List<Integer> and a List<Double> for reading numbers?
- List<Integer> is a subtype of List<Number>.
- Which map keeps its keys sorted?
- What is the contract between equals and hashCode?
- What happens when you call add on a list created by List.of(...)?
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
| Interface | Method | Shape |
|---|---|---|
Function<T, R> | apply | T to R |
Predicate<T> | test | T to boolean |
Consumer<T> | accept | T to nothing |
Supplier<T> | get | nothing to T |
UnaryOperator<T>, BinaryOperator<T> | apply | T 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
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));Optionalis a return type that says "there may be no result", in place ofnull.Optional.of(x)throws on null; useOptional.ofNullable(x)when x may be null.- Calling
get()on an empty Optional throwsNoSuchElementException. - Do not use it for fields or method parameters.
@FunctionalInterface: the compiler then rejects a second abstract method.Check yourself
- What is a functional interface?
- Which interface represents a function from T to boolean?
- Which local variables can a lambda use?
- What does String::length represent?
- What does Optional.of(null) do?
- What is the main purpose of Optional?
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, flatMap | collect, toList, forEach |
sorted, distinct | count, reduce, sum |
limit, skip, peek | findFirst, anyMatch, allMatch |
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.forEach adding to an outside list.Check yourself
- When do the intermediate operations of a stream execute?
- What happens if you use a stream a second time?
- Which operation turns a stream of lists into one stream of their elements?
- Which collector groups elements into a Map by a key?
- Which of these is a terminal operation?
- When is a parallel stream a poor choice?
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)); // trueequals, 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: sealedWith 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
| Feature | Example |
|---|---|
| Text blocks | """ multi-line strings """ |
var | Local variable type inference |
| Enhanced enums | Enums with fields, constructors and methods |
| Helpful NullPointerException messages | They name the null variable |
Check yourself
- What does the compiler generate for a record?
- How do you read the x component of record Point(int x, int y)?
- The fields of a record can be reassigned after construction.
- What does a sealed interface with a permits clause do?
- What does if (obj instanceof String s) do?
- Why can a switch over a sealed type omit default?
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.
| Tool | Gives |
|---|---|
synchronized | Mutual exclusion and visibility |
volatile | Visibility of the latest value only; n++ is still not atomic |
AtomicInteger | Lock-free atomic operations: incrementAndGet() |
ConcurrentHashMap | A thread-safe map with atomic merge and computeIfAbsent |
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
- What is the difference between t.start() and t.run()?
- Why use a thread pool?
- What does volatile guarantee?
- Which class gives an atomic counter without locks?
- What does Future.get() do?
- What are virtual threads best suited for?
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)); }
}Maven and Gradle
| Maven | Gradle | |
|---|---|---|
| Build file | pom.xml | build.gradle(.kts) |
| Style | Declarative XML, fixed lifecycle | Script in Groovy or Kotlin |
| Run tests | mvn test | gradle 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
- In which order are resources closed in try-with-resources?
- Why pass the original exception as the cause when wrapping?
- Which JUnit 5 assertion checks that code throws?
- What does @BeforeEach do?
- What is Maven's build file?
- Which interface must a class implement to be used in try-with-resources?