Optional<T> is a box that holds a value or nothing, and forces the caller to think about the nothing case. Optional.of(x), Optional.empty(), and Optional.ofNullable(maybeNull) make one; isPresent(), orElse(fallback), map(f), and ifPresent(action) use it. Returning Optional<Book> from a search says "may not be found" in the signature, where returning null says nothing and crashes later.
Streams return optionals from findFirst() and max(...). The rule of thumb: use Optional as a return type for lookups that can miss; do not store it in fields or pass it as a parameter.
Optional<String> first = words.stream().filter(w -> w.startsWith("b")).findFirst();
System.out.println(first.orElse("none"));
System.out.println(first.map(String::length).orElse(0));Your task
Write static Optional<String> firstLong(List<String> words, int min) returning the first word longer than min characters, static String firstLongOr(List<String> words, int min, String fallback) using it, and static Optional<Integer> parse(String text) returning the number in the text or an empty optional when it is not a whole number.
Hint 1
for (String w : words) if (w.length() > min) return Optional.of(w); return Optional.empty(); or words.stream().filter(...).findFirst().
Hint 2
firstLongOr: return firstLong(words, min).orElse(fallback); parse: try { return Optional.of(Integer.parseInt(text)); } catch (NumberFormatException e) { return Optional.empty(); }
Show the solution
import java.util.*;
public class Main {
static Optional<String> firstLong(List<String> words, int min) {
return words.stream().filter(w -> w.length() > min).findFirst();
}
static String firstLongOr(List<String> words, int min, String fallback) {
return firstLong(words, min).orElse(fallback);
}
static Optional<Integer> parse(String text) {
try {
return Optional.of(Integer.parseInt(text));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static void main(String[] args) {
System.out.println(firstLongOr(List.of("a", "abcd"), 3, "none") + " " + parse("42").orElse(-1));
}
}