Skip to content

Commit f894520

Browse files
committed
Optional.ofNullable is generally more usable in conjucture with .orElse()
1 parent 1a59600 commit f894520

1 file changed

Lines changed: 5 additions & 1 deletion

File tree

README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,13 +344,17 @@ Optionals are not functional interfaces, but nifty utilities to prevent `NullPoi
344344
Optional is a simple container for a value which may be null or non-null. Think of a method which may return a non-null result but sometimes return nothing. Instead of returning `null` you return an `Optional` in Java 8.
345345

346346
```java
347-
Optional<String> optional = Optional.of("bam");
347+
Optional<String> optional = Optional.ofNullable("bam");
348348

349349
optional.isPresent(); // true
350350
optional.get(); // "bam"
351351
optional.orElse("fallback"); // "bam"
352352

353353
optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b"
354+
355+
List<String> initials = null; // uninitilized
356+
initials = Optional.ofNullable(initials).orElse(Arrays.asList("abc", "def")); // ["abc", "def"]
357+
354358
```
355359

356360
## Streams

0 commit comments

Comments
 (0)