Null causes many crashes. Optional is a small box that either holds a value, or is empty. It makes it clear that a value might be missing, and forces you to think about it.
Find user returns an Optional. Optional dot of holds a value, and Optional dot empty holds nothing. Is present checks if there's a value. Or else gives a fallback, when it's empty. Map changes the value, only if there is one. And if present runs code only when there's a value. Run it. True, false. Ana, then guest. Ana in capitals. And found ana prints only once.
Main.javajava
import java.util.*;public class Main { static Optional<String> findUser(int id) { if (id == 1) return Optional.of("ana"); return Optional.empty(); } public static void main(String[] args) { Optional<String> a = findUser(1); Optional<String> b = findUser(7); System.out.println(a.isPresent() + " " + b.isPresent()); System.out.println(a.get()); System.out.println(b.orElse("guest")); System.out.println(a.map(String::toUpperCase).orElse("?")); b.ifPresent(name -> System.out.println("Found " + name)); a.ifPresent(name -> System.out.println("Found " + name)); }}
Stream steps like find first, and max, return an Optional, because there might be no answer. Here, find first finds a price over thirty, but nothing is over a hundred. Run it. Forty, and zero as the fallback. The max is forty.
Main.javajava
import java.util.*;public class Main { public static void main(String[] args) { List<Integer> prices = List.of(12, 40, 7, 25); Optional<Integer> firstBig = prices.stream().filter(p -> p > 30).findFirst(); Optional<Integer> huge = prices.stream().filter(p -> p > 100).findFirst(); System.out.println(firstBig.orElse(0) + " " + huge.orElse(0)); System.out.println(prices.stream().max(Integer::compare).get()); }}
Use Optional as a return type, when a result might be missing. Prefer or else, map, and if present, over get. Get throws an exception if the box is empty. And never put null inside an Optional.