June 2018
Beginner
722 pages
18h 47m
English
The object of java.util.Optional is used to avoid returning null, as it may cause a NullPointerException. Instead, an Optional object provides methods that can be used to check the value presence and to substitute it if there is no value. For example:
List<String> list = List.of("1", "2", "3", "4", "5");String result = list.stream().filter(e -> "42".equals(e)) .findAny().or(() -> Optional.of("Not found")).get();System.out.println(result); //prints: Not foundresult = list.stream().filter(e -> "42".equals(e)) .findAny().orElse("Not found");System.out.println(result); //prints: Not found Supplier<String> trySomethingElse = () -> { //Code that tries something else return "43";};result = list.stream().filter(e -> "42".equals(e)) ...
Read now
Unlock full access