Chapter 12
Java 8 Features
5 topics · 1 sections · beginner-friendly study notes · Updated
Java 8 added functional-style programming to Java: lambda expressions, functional interfaces, the Stream API, Optional and method references.
Together they replace verbose loops and anonymous classes with short, readable pipelines.
Java 8 style is now the default in modern Java code, and lambda / stream questions are asked in almost every interview.
Filtering and transforming lists, grouping records, reporting, event handlers, Spring and JPA code, asynchronous callbacks.
Lambda Expressions in Java
A lambda expression is an anonymous function — a block of code with parameters and an optional return value — written as (parameters) -> expression or (parameters) -> { statements; }. It can be used wherever a functional interface is expected.
In short: A lambda is a tiny nameless method you can pass around like a value.
Think about it
They remove boilerplate of anonymous classes and make functional-style APIs such as streams practical. Instead of writing a full job description each time, you hand over a sticky note with just the instruction.
The compiler infers the parameter types from the target functional interface (target typing), so (a, b) -> a + b needs no types.
Rules: parentheses are optional for a single parameter; braces and the return keyword are needed for multi-statement bodies; a single expression returns its value automatically.
A lambda can use local variables of the enclosing method only if they are final or effectively final (never reassigned) because the value is copied.
Inside a lambda this refers to the enclosing class (unlike an anonymous class where this is the anonymous object).
Lambdas compile via invokedynamic, not into separate inner class files.
They enable behaviour parameterisation: passing logic to forEach, removeIf, sort, computeIfAbsent, threads and streams.
Keep lambdas short; extract long logic into a named method and use a method reference.
Key points
- Lambda: Anonymous function: params
->body. - Target typing: Compiler decides the lambda type from the context.
- Effectively final: Local variable that is never reassigned after initialisation.
- Closure / capture: Using outside local variables inside the lambda.
- Syntax: (a, b)
->a + b | x->x * x | ()->System.out.println("hi"). - Works only with functional interfaces (exactly one abstract method).
- Captured locals must be effectively final.
- this inside a lambda = the enclosing object.
Example
CodeLambda syntax and typical uses:
import java.util.*;
import java.util.function.*;
public class LambdaDemo {
interface Calculator { int calc(int a, int b); }
public static void main(String[] args) {
// Anonymous class vs lambda
Runnable old = new Runnable() {
public void run() { System.out.println("anonymous"); }
};
Runnable lam = () -> System.out.println("lambda");
old.run(); // anonymous
lam.run(); // lambda
Calculator add = (a, b) -> a + b;
Calculator mul = (a, b) -> { int r = a * b; return r; };
System.out.println(add.calc(3, 4) + " " + mul.calc(3, 4)); // 7 12
List<String> names = new ArrayList<>(List.of("Ravi", "amit", "Neha"));
names.sort((x, y) -> x.compareToIgnoreCase(y));
System.out.println(names); // [amit, Neha, Ravi]
names.forEach(n -> System.out.print(n.length() + " ")); // 4 4 4
System.out.println();
names.removeIf(n -> n.startsWith("N"));
System.out.println(names); // [amit, Ravi]
int base = 10; // effectively final
Function<Integer, Integer> addBase = x -> x + base;
System.out.println(addBase.apply(5)); // 15
// base = 20; // would make the lambda above a compile error
BiFunction<Integer, Integer, Integer> power = (b, e) -> {
int r = 1;
for (int i = 0; i < e; i++) r *= b;
return r;
};
System.out.println(power.apply(2, 10)); // 1024
Thread t = new Thread(() -> System.out.println("running in " + Thread.currentThread().getName()));
t.start();
}
}Functional Interfaces in Java
A functional interface is an interface with exactly one abstract method (it may also have default, static and Object-method declarations). It can be implemented with a lambda or method reference and is optionally marked with @FunctionalInterface.
In short: An interface that asks for just one thing to be implemented, so a lambda can fill it in.
Think about it
They give lambdas a type, and the standard set means you rarely need to write your own. Standard electrical sockets: any appliance (lambda) with the right plug (single method shape) works.
@FunctionalInterface makes the compiler reject the interface if it ever gets a second abstract method.
The package java.
util.
function provides ready-made types: Predicate<T> (test → boolean), Function<T,R> (apply), Consumer<T> (accept, no result), Supplier<T> (get, no input), UnaryOperator<T> (T→T), BinaryOperator<T> ((T,T)→T), BiFunction<T,U,R>, plus primitive versions (IntPredicate, IntFunction, ToIntFunction, IntBinaryOperator...
) that avoid boxing.
Old interfaces such as Runnable, Callable, Comparator and ActionListener are functional too.
Composition via default methods: `Predicate.
and/or/negate, Function.
andThen/compose, Consumer.
andThen, Comparator.
thenComparing/reversed`.
Default methods let interfaces evolve without breaking old implementations, which is how Java 8 added stream() to Collection.
Key points
- SAM: Single Abstract Method interface.
- @FunctionalInterface: Annotation that enforces the one-abstract-method rule.
- Predicate: T
→boolean. - Function: T
→R. - Consumer / Supplier: T
→void / ()→T.
Example
CodeBuilt-in and custom functional interfaces:
import java.util.function.*;
public class FunctionalDemo {
@FunctionalInterface
interface Validator {
boolean validate(String s);
default Validator and(Validator other) {
return s -> validate(s) && other.validate(s);
}
}
public static void main(String[] args) {
Predicate<Integer> even = n -> n % 2 == 0;
Predicate<Integer> big = n -> n > 10;
System.out.println(even.test(4)); // true
System.out.println(even.negate().test(4)); // false
System.out.println(even.and(big).test(12)); // true
System.out.println(even.or(big).test(7)); // false
Function<Integer, Integer> dbl = x -> x * 2;
Function<Integer, Integer> inc = x -> x + 1;
System.out.println(dbl.andThen(inc).apply(5)); // 11 (double, then +1)
System.out.println(dbl.compose(inc).apply(5)); // 12 (+1, then double)
Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!");
shout.accept("hello"); // HELLO!
Supplier<Double> half = () -> 0.5;
System.out.println(half.get()); // 0.5
UnaryOperator<String> trim = String::trim;
BinaryOperator<Integer> max = BinaryOperator.maxBy(Integer::compare);
System.out.println(trim.apply(" hi ") + "|" + max.apply(3, 9)); // hi|9
IntBinaryOperator sum = (a, b) -> a + b; // no boxing
System.out.println(sum.applyAsInt(2, 3)); // 5
Validator notEmpty = s -> !s.isEmpty();
Validator hasAt = s -> s.contains("@");
System.out.println(notEmpty.and(hasAt).validate("a@b.com")); // true
System.out.println(notEmpty.and(hasAt).validate("abc")); // false
}
}Predicate<T>
boolean test(T t); with and(), or(), negate().
Function<T,R>
R apply(T t); with andThen() and compose().
Consumer<T> and Supplier<T>
void accept(T t) consumes a value; T get() produces one.
UnaryOperator / BinaryOperator
Special Function and BiFunction where all types are the same.
Stream API in Java
The Stream API (java.util.stream) lets you process sequences of elements declaratively through a pipeline: a source (collection, array, generator), zero or more lazy intermediate operations (filter, map, sorted ...) and one terminal operation (collect, forEach, reduce, count ...) that triggers execution.
In short: A stream is a conveyor belt: items come from a source, pass through stations (filter, map) and end in a box (list, sum, map).
Think about it
Pipelines express what you want instead of how to loop, making filtering, grouping and aggregation short and less error-prone. A factory line: raw items enter, are inspected (filter), reshaped (map), and packed (collect) at the end.
A stream does not store data and does not modify its source.
Intermediate operations are lazy: nothing runs until a terminal operation is called, and elements flow one by one through the whole pipeline (so short-circuit operations like limit, findFirst and anyMatch can stop early).
A stream can be consumed only once; reusing it throws IllegalStateException.
Common intermediate ops: filter, map, flatMap, distinct, sorted, peek, limit, skip.
Terminal ops: forEach, collect, reduce, count, min, max, sum (on primitive streams), anyMatch/allMatch/noneMatch, findFirst/findAny, toArray.
Collectors: toList, toSet, toMap, joining, counting, summingInt, averagingInt, groupingBy, partitioningBy.
Primitive streams (IntStream, LongStream, DoubleStream) avoid boxing: `IntStream.
rangeClosed(1, 5), mapToInt, sum(), average()`.
parallelStream() splits the work over the common ForkJoinPool; use only for large, CPU-heavy, stateless operations.
Do not mutate shared state inside lambdas.
Key points
- Source: Where the stream starts:
list.stream(),Arrays.stream(a),Stream.of(...). - Intermediate operation: Lazy step that returns another stream.
- Terminal operation: Triggers processing and produces a result or side effect.
- Collector: Strategy to accumulate stream elements into a result.
- Short-circuit: Operation that can finish without reading all elements.
- No terminal operation = nothing executes.
- A stream can be used only once.
- map transforms 1:1; flatMap flattens 1:many.
- Streams do not change the original collection.
Read more
Example
CodeStream pipelines: filter, map, reduce, collect:
import java.util.*;
import java.util.stream.*;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> nums = List.of(5, 2, 8, 1, 9, 2, 6);
List<Integer> evenSquares = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println(evenSquares); // [4, 36, 64]
int sum = nums.stream().mapToInt(Integer::intValue).sum();
System.out.println(sum); // 33
System.out.println(nums.stream().reduce(0, Integer::sum)); // 33
System.out.println(nums.stream().max(Integer::compare).get());// 9
System.out.printf("%.2f%n", nums.stream().mapToInt(i -> i).average().getAsDouble()); // 4.71
System.out.println(nums.stream().anyMatch(n -> n > 8) + " " + nums.stream().allMatch(n -> n > 0)); // true true
System.out.println(nums.stream().skip(2).limit(3).collect(Collectors.toList())); // [8, 1, 9]
List<String> words = List.of("apple", "fig", "banana", "kiwi", "cherry");
System.out.println(words.stream()
.filter(w -> w.length() > 4)
.map(String::toUpperCase)
.collect(Collectors.joining(", "))); // APPLE, BANANA, CHERRY
Map<Integer, List<String>> byLen = words.stream()
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));
System.out.println(byLen); // {3=[fig], 4=[kiwi], 5=[apple], 6=[banana, cherry]}
Map<Boolean, Long> parts = nums.stream()
.collect(Collectors.partitioningBy(n -> n > 4, Collectors.counting()));
System.out.println(parts); // {false=3, true=4}
System.out.println(IntStream.rangeClosed(1, 5).reduce(1, (a, b) -> a * b)); // 120
List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(4, 5));
System.out.println(nested.stream().flatMap(List::stream).collect(Collectors.toList())); // [1, 2, 3, 4, 5]
Stream<String> s = words.stream();
s.count();
try { s.count(); }
catch (IllegalStateException e) { System.out.println("Stream already used"); }
}
}Optional Class in Java
Optional<T> (java.util) is a container object that may or may not hold a non-null value. It is used mainly as a method return type to say clearly that a result can be absent, instead of returning null.
In short: Optional is a box that is either holding one value or empty, so you are forced to think about the empty case.
Think about it
NullPointerException is the most common Java bug; Optional makes absence explicit and encourages safe handling. A parcel slot that either has a parcel or a card saying "empty" — you always look at the card before reaching in.
Create with `Optional.
of(v) (NullPointerException if v is null), Optional.
ofNullable(v) or Optional.
empty()`.
Read safely with `orElse(default)` (default is always evaluated), orElseGet(supplier) (lazy), `orElseThrow(...
), ifPresent(consumer), ifPresentOrElse (Java 9), isPresent() / isEmpty()` (Java 11).
Transform with map, flatMap and filter, which allow null-free chains such as `user.
map(User::getAddress).
map(Address::getCity).
orElse("Unknown")`.
get() throws NoSuchElementException on empty and should be avoided without a check.
Best practices: use as a return type, not as a field, method parameter or collection element; never return null from a method that returns Optional; do not use Optional for primitives (use OptionalInt).
Optional is not Serializable.
Stream terminal operations such as findFirst, max, min and reduce return Optional.
Key points
- Optional.of: Wraps a non-
nullvalue. - ofNullable: Wraps a value that may be
null. - orElse / orElseGet: Default value / lazily computed default.
- orElseThrow: Throw a chosen exception when empty.
Optional.of(null)throws NullPointerException.- orElse evaluates its argument even when a value is present; orElseGet does not.
- Do not use Optional as a field or parameter type.
get()on an empty Optional throws NoSuchElementException.
Example
CodeCreating, transforming and unwrapping Optional:
import java.util.*;
public class OptionalDemo {
static Optional<String> findEmail(String user) {
Map<String, String> db = Map.of("amit", "amit@mail.com");
return Optional.ofNullable(db.get(user));
}
static String expensiveDefault() {
System.out.println("computing default...");
return "none@mail.com";
}
public static void main(String[] args) {
Optional<String> a = findEmail("amit");
Optional<String> b = findEmail("zed");
System.out.println(a.isPresent() + " " + b.isPresent()); // true false
System.out.println(a.get()); // amit@mail.com
System.out.println(b.orElse("unknown")); // unknown
a.ifPresent(e -> System.out.println("Found " + e)); // Found amit@mail.com
System.out.println(a.map(String::toUpperCase).get()); // AMIT@MAIL.COM
System.out.println(a.filter(e -> e.endsWith(".org")).isPresent()); // false
System.out.println(a.orElse(expensiveDefault())); // computing default... then amit@mail.com
System.out.println(a.orElseGet(() -> expensiveDefault())); // amit@mail.com (no computing)
try {
b.orElseThrow(() -> new IllegalStateException("No email"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // No email
}
try { Optional.of(null); }
catch (NullPointerException e) { System.out.println("of(null) fails"); }
String city = Optional.ofNullable((String) null).map(String::trim).orElse("Unknown");
System.out.println(city); // Unknown
System.out.println(Optional.empty().isEmpty()); // true (Java 11)
}
}Method References in Java
A method reference is a compact notation Class::method that refers to an existing method (or constructor) without calling it, and can be used instead of a lambda that only calls that method.
In short: If your lambda just forwards to a method, write the method name with :: instead.
Think about it
Shorter and often more readable than lambdas that merely delegate, and heavily used in stream code. Instead of writing "ask Ravi to open the door", you simply point at Ravi (the method) and say "him".
Four kinds: (1) static method — `Integer::parseInt` equals `s -> Integer.
parseInt(s)`; (2) instance method of a particular object (bound) — `System.
out::println` equals `x -> System.
out.
println(x), and str::length`; (3) instance method of an arbitrary object of a type (unbound) — `String::toUpperCase` equals `s -> s.
toUpperCase()` where the first lambda parameter becomes the receiver; (4) constructor — `ArrayList::new` equals `() -> new ArrayList<>(), Person::new` and array constructors int[]::new.
The compiler checks that the referenced method matches the functional interface signature.
Overloaded methods are resolved from the target type.
Method references make stream pipelines more readable (`map(String::trim), forEach(System.
out::println), toArray(String[]::new)`), but a lambda is clearer when extra logic is needed.
Key points
Read more
Example
CodeThe four kinds of method references:
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class MethodRefDemo {
static class Person {
String name;
Person(String name) { this.name = name; }
String getName() { return name; }
@Override public String toString() { return "Person:" + name; }
}
static boolean isLong(String s) { return s.length() > 3; }
public static void main(String[] args) {
// 1. static method reference
Function<String, Integer> parse = Integer::parseInt;
System.out.println(parse.apply("42") + 1); // 43
Predicate<String> longWord = MethodRefDemo::isLong;
System.out.println(longWord.test("java")); // true
// 2. bound instance method reference
List<String> items = List.of("a", "b", "c");
items.forEach(System.out::print); // abc
System.out.println();
String prefix = "Hello, ";
Function<String, String> greet = prefix::concat;
System.out.println(greet.apply("Java")); // Hello, Java
// 3. unbound instance method reference
Function<String, String> up = String::toUpperCase;
System.out.println(up.apply("lambda")); // LAMBDA
System.out.println(Stream.of("kiwi", "fig").map(String::length).collect(Collectors.toList())); // [4, 3]
// 4. constructor references
Supplier<List<String>> maker = ArrayList::new;
List<String> fresh = maker.get();
fresh.add("x");
System.out.println(fresh); // [x]
Function<String, Person> create = Person::new;
System.out.println(create.apply("Neha")); // Person:Neha
String[] arr = Stream.of("p", "q").toArray(String[]::new);
System.out.println(arr.length); // 2
List<Person> people = Stream.of("Ravi", "Amit").map(Person::new).collect(Collectors.toList());
people.sort(Comparator.comparing(Person::getName));
System.out.println(people); // [Person:Amit, Person:Ravi]
}
}Static
Integer::parseInt, Math::max, String::valueOf.
Bound instance
System.
out::println, myObject::process.
Unbound instance
String::length, String::toUpperCase, Person::getName.
Constructor
ArrayList::new, StringBuilder::new, String[]::new.
Solved examples
Rewrite list.sort(new Comparator<String>() { public int compare(String a, String b) { return a.length() - b.length(); } }) using a lambda and then a method-based comparator.
Shorter code
Formula Applied:—Approach note: comparingInt avoids the overflow risk of subtracting.
From List<Integer> nums = List.of(1,2,3,4,5,6) get the sum of squares of the even numbers.
Single number
Formula Applied:—Approach note: Use mapToInt before sum(); Stream<Integer> has no sum().
Group words ["bat","car","bus","cat","dog"] by their first letter.
Map<Character, List<String>>
Formula Applied:—Approach note: groupingBy returns a HashMap by default, so key order is not guaranteed.
Given user.getAddress().getCity() where address may be null, return the city or "Unknown" without if-statements.
Null-safe expression
Formula Applied:—Approach note: map automatically returns an empty Optional when the mapper returns null.
Real-world applications
Using Java 8 Features in real projects
Filtering and transforming lists, grouping records, reporting, event handlers, Spring and JPA code, asynchronous callbacks.
Common mistakes
❌ Myth: Streams store the data like a collection.
Why this is wrong: A stream is a view of a pipeline over a source.
✅ Verified Truth: Streams do not store elements and do not modify the source.
⚠️ Exam Tip: Say: streams are lazy and single-use.
❌ Myth: A stream can be reused after a terminal operation.
Why this is wrong: It is closed after consumption.
✅ Verified Truth: Create a new stream; reuse throws IllegalStateException.
⚠️ Exam Tip: Common exception question.
❌ Myth: Lambdas can modify any local variable.
Why this is wrong: Captured locals must be effectively final.
✅ Verified Truth: Use an array, AtomicInteger or a field if mutation is really needed.
⚠️ Exam Tip: Compile error: local variables referenced from a lambda must be final or effectively final.
❌ Myth: Optional.orElse is lazy.
Why this is wrong: Its argument is evaluated every time.
✅ Verified Truth: Use orElseGet(() -> ...) for expensive defaults.
⚠️ Exam Tip: Frequent follow-up in interviews.
Revision notes
Java 8 added functional-style programming to Java: lambda expressions, functional interfaces, the Stream API, Optional and method references. Together they replace verbose loops and anonymous classes with short, readable pipelines.
High-Yield Quick Revision Points
- Lambda: (params) -> body; captured locals must be effectively final
- Functional interface: one abstract method; Predicate, Function, Consumer, Supplier
- Stream = source + lazy intermediates + one terminal; single use
- collect(groupingBy / joining / toList), reduce, mapToInt().sum()
- Optional: of / ofNullable / empty; orElse vs orElseGet; avoid get()
- Method refs: Class::static, obj::method, Class::instance, Class::new
Practice questions
What is a functional interface?
Which interface has the method boolean test(T t)?
Which is an intermediate stream operation?
What does Optional.of(null) do?
System.out::println is which kind of method reference?
Which operation is needed to start processing a stream pipeline?