A lambda implements a functional interface (one abstract method). The compiler infers the SAM type from the target (assignment, return, argument).
Predicate<String> blank = s -> s == null || s.isBlank();
Predicate<String> blank2 = String::isBlank; // NPE if the element is null
Comparator<User> byName = Comparator.comparing(User::name);
Runnable r = () -> log.info("go");
this if they touch instance members — that can keep an enclosing object alive (listener leaks).Type::staticMethod, obj::instanceMethod, Type::instanceMethod (the first SAM argument is the receiver), Type::new.this to be the listener, a lambda’s this is the enclosing instance.Function cannot throw checked exceptions. Wrap or use a small helper — do not invent a parallel stream API.When not to lambda: the body is longer than a glance; you need to debug it often (give it a name); the inference is unreadable.
Optional<T> is a value-based container: present or empty. It exists so a return type can say “absence is normal” without null.
Optional<User> u = repo.findById(id);
User user = u.orElseThrow(() -> new NoSuchElementException(id));
String name = u.map(User::name).orElse("anonymous");
// Incorrect
u.get(); // throws if empty — use orElseThrow with context
u.orElse(loadDefault()); // loadDefault always runs
u.orElseGet(this::loadDefault); // lazy — correct
if (u.isPresent()) { u.get(); } // usually a smell; use map/ifPresent/orElse
orElse vs orElseGet: orElse(x) evaluates x always. If x is a constructor or a lookup, you just paid for a value you throw away. Use orElseGet.
Optional.of(null) throws. Optional.ofNullable is the null-tolerant factory. orElse(null) is allowed but usually means you wanted a nullable return after all — be honest at the API boundary.
Java 9+: ifPresentOrElse, or, stream(). Java 11: isEmpty.
A Stream is a single-use pipeline: source → intermediate ops (lazy) → one terminal op (eager). It is not a collection. You cannot traverse it twice.
List<String> names = users.stream()
.filter(User::active)
.map(User::name)
.map(String::strip)
.filter(s -> !s.isEmpty())
.distinct()
.sorted()
.toList(); // Java 16, unmodifiable
| Kind | Examples | Notes |
|---|---|---|
| Source | list.stream(), Stream.of, Files.lines, IntStream.range | Files.lines must be closed (TWR on the Stream). |
| Intermediate | filter, map, flatMap, distinct, sorted, peek, limit, skip | Lazy. peek is for debugging, not logic. |
| Terminal | forEach, collect, reduce, count, anyMatch, findFirst, toList | Consumes the stream. A second terminal throws. |
flatMap maps each element to a stream and concatenates. Use it to unwrap Optional (Optional::stream, Java 9) or split lines.map vs mapToInt: primitive streams avoid boxing when you are aggregating numbers.findFirst vs findAny matters under parallel.collect(Collectors.toUnmodifiableList()) (10) / toList() (16) vs toCollection(ArrayList::new) when you must mutate later.parallelStream() uses the common ForkJoinPool. It helps CPU-bound work on large, splittable sources with associative operations. It hurts small lists, anything that blocks, and anything that mutates shared state.
// Incorrect List<String> out = new ArrayList<>(); list.parallelStream().forEach(out::add); // race // Correct List<String> out = list.parallelStream().map(...).toList();
forEach is the wrong terminal; use forEachOrdered or collect.Map<Dept, List<User>> byDept = users.stream()
.collect(Collectors.groupingBy(User::dept));
Map<String, User> byId = users.stream()
.collect(Collectors.toMap(User::id, u -> u, (a, b) -> a)); // merge on duplicate keys
String csv = names.stream().collect(Collectors.joining(","));
int sum = orders.stream().collect(Collectors.summingInt(Order::cents));
toMap without a merge function throws on duplicate keys. Always think about duplicates.groupingBy downstream: groupingBy(User::dept, Collectors.counting()).collect just to stream again if one pipeline will do.get(i), no size before a terminal that is not count).peek with side effects that you depend on — the pipeline may short-circuit (findFirst) and skip them.orElse(new X()) allocating every time.List<Optional<T>>.Files.lines without try-with-resources (leaks a file descriptor).Stream.iterate, generate) without limit.// Incorrect stream.peek(this::save).count(); // count may skip peek on some empty/short-circuit cases; also ugly // Correct — a loop or forEach as the terminal if save is the point for (var item : items) save(item);
~ Good luck with your revision! ~