OptionalemptyOptional = Optional.empty(); System.out.println(emptyOptional.isPresent()); // false
ListIn this example, a list of names is created and filtered to find a name starting with "C". If none is found, an "Unknown" name is returned. The returned name is then used to create an Optional object using the ofNullable() method. An empty Optional object is also created using the empty() method. The isPresent() method is called on both Optionals to determine if the value is present. The java.util.Optional class is defined in the java.util package library.names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); String name = names.stream() .filter(n -> n.startsWith("C")) .findFirst() .orElseGet(() -> "Unknown"); Optional optionalName = Optional.ofNullable(name); Optional emptyOptional = Optional.empty(); System.out.println(optionalName.isPresent()); // true System.out.println(emptyOptional.isPresent()); // false