Optional is a container object that may or may not contain a value. You can check if a value is present by calling the isPresent() method. If isPresent() returns true you can use the get() method to return the value.
Null pointer exception is a real problem in programming and that we must handle it with care.
How to create an Optional
String name = "Folau"; // name can't be null or else you will get a NullPointerException Optional<String> opt = Optional.of(name);
If we expect null values, we can use the ofNullable method which does not throw a NullPointerException
String name = "Folau"; Optional<String> opt = Optional.ofNullable(name); String name = null; // this won't throw a NullPointerException Optional<String> opt = Optional.ofNullable(name);
Check if Optional is empty or not
The Optional.isPresent() method is used to check if an Optional has a value or not. It returns true if the Optional has value otherwise it returns false.
String name = "Folau"; Optional<String> opt = Optional.ofNullable(name); if (opt.isPresent()) { System.out.println("Value available."); } else { System.out.println("Value not available."); }
The Optional.ifPresent() method is used to execute a lambda function (on the value) if Optional is not empty. if Optional is empty, do nothing.
opt.ifPresent(n -> { System.out.println(n); });
Optional.orElse(T other) returns the value if present, otherwise return other of same data type
Optional.orElseGet(Supplier T) returns the value if present, otherwise invoke T and return the result of that call.
//when using orElse(), whether the wrapped value is present or not, the default object is created. //So in this case, we have just created one redundant object that is never used. String n = opt.orElse(getRealName()); System.out.println(n); String na = opt.orElseGet(() -> getRealName()); System.out.println(na); .... private String getRealName() { System.out.println("getRealName()"); return "Lisa"; } // Run program result getRealName() Folau Folau
Optional.filter(Predicate T) – If a value is present, and the value matches the given predicate, return an Optional
describing the value, otherwise return an empty Optional
.
Optional<Integer> ageOpt = Optional.ofNullable(20); boolean underAgeForBeer = ageOpt.filter(age -> { return (age >= 21); }).isPresent(); System.out.println("underAgeForBeer = " + underAgeForBeer);
Optional.map(Function mapper) – If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional
describing the result. Otherwise return an empty Optional
.
Optional<String> optFileName = Optional.ofNullable("file.pdf"); Optional<File> optFile = optFileName.map(fileName -> new File(fileName));