Tutorial by Examples

Don't just use Optional.get() since that may throw NoSuchElementException. The Optional.orElse(T) and Optional.orElseGet(Supplier<? extends T>) methods provide a way to supply a default value in case the Optional is empty. String value = "something"; return Optional.ofNullable(v...

Map

Use the map() method of Optional to work with values that might be null without doing explicit null checks: (Note that the map() and filter() operations are evaluated immediately, unlike their Stream counterparts which are only evaluated upon a terminal operation.) Syntax: public <U> Option...
Use the orElseThrow() method of Optional to get the contained value or throw an exception, if it hasn't been set. This is similar to calling get(), except that it allows for arbitrary exception types. The method takes a supplier that must return the exception to be thrown. In the first example, the...
filter() is used to indicate that you would like the value only if it matches your predicate. Think of it like if (!somePredicate(x)) { x = null; }. Code examples: String value = null; Optional.ofNullable(value) // nothing .filter(x -> x.equals("cool string"))// this is nev...
OptionalDouble, OptionalInt and OptionalLong work like Optional, but are specifically designed to wrap primitive types: OptionalInt presentInt = OptionalInt.of(value); OptionalInt absentInt = OptionalInt.empty(); Because numeric types do have a value, there is no special handling for null. Empt...
Optional<String> optionalWithValue = Optional.of("foo"); optionalWithValue.ifPresent(System.out::println);//Prints "foo". Optional<String> emptyOptional = Optional.empty(); emptyOptional.ifPresent(System.out::println);//Does nothing.
The normal orElse method takes an Object, so you might wonder why there is an option to provide a Supplier here (the orElseGet method). Consider: String value = "something"; return Optional.ofNullable(value) .orElse(getValueThatIsHardToCalculate()); // returns "some...
flatMap is similar to map. The difference is described by the javadoc as follows: This method is similar to map(Function), but the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional. In other words, when you chain a...

Page 1 of 1