|
| 1 | +package com.learn.optional; |
| 2 | + |
| 3 | +import com.learn.data.Student; |
| 4 | +import com.learn.data.StudentDataBase; |
| 5 | + |
| 6 | +import java.util.Optional; |
| 7 | + |
| 8 | +public class OptionalOrElseExample { |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + |
| 12 | + System.out.println("Optional orElse() : " + optionalOrElse()); |
| 13 | + |
| 14 | + System.out.println("Optional orElseGet() : " + optionalOrElseGet()); |
| 15 | + |
| 16 | + System.out.println("Optional orElseThrow() : " + optionalOrElseThrow()); |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * <p> |
| 21 | + * orElse(T) : it accepts the actual value |
| 22 | + * If a value is present, returns the value, otherwise returns |
| 23 | + * other value passed. |
| 24 | + * </p> |
| 25 | + * @return |
| 26 | + */ |
| 27 | + public static String optionalOrElse() { |
| 28 | + |
| 29 | + Optional<Student> studentOptional = Optional.ofNullable(StudentDataBase.studentSupplier.get()); |
| 30 | + |
| 31 | + /** |
| 32 | + * Optional<Student> studentOptional = Optional.ofNullable(null); // it return Optional.empty() |
| 33 | + * it's going try to map the student object and try to get Name. but since it is empty, |
| 34 | + * it won't be able to execute map, and execute the orElse and return John. |
| 35 | + */ |
| 36 | + return studentOptional.map(Student::getName).orElse("John"); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * <p> |
| 41 | + * orElseGet(Supplier) : it's going to accept a supplier. |
| 42 | + * If a value is present, returns the value, otherwise returns the result |
| 43 | + * produced by the supplying function. |
| 44 | + * </p> |
| 45 | + * @return |
| 46 | + */ |
| 47 | + public static String optionalOrElseGet() { |
| 48 | + |
| 49 | + Optional<Student> studentOptional = Optional.ofNullable(StudentDataBase.studentSupplier.get()); |
| 50 | + return studentOptional.map(Student::getName).orElseGet(() -> "Default"); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @apiNote |
| 55 | + * There are 2 different versions of orElseThrow(). |
| 56 | + * <ul> |
| 57 | + * <li>orElseThrow() : it throws NoSuchElementException if no value is present </li> |
| 58 | + * <li>orElseThrow(Supplier<? extends X> exceptionSupplier) : it accepts exceptionSupplier the |
| 59 | + * supplying function that produces an exception to be thrown</li> |
| 60 | + * </ul> |
| 61 | + * |
| 62 | + */ |
| 63 | + public static String optionalOrElseThrow() { |
| 64 | + Optional<Student> studentOptional = Optional.ofNullable(null); |
| 65 | + return studentOptional.map(Student::getName) |
| 66 | + .orElseThrow(() -> new RuntimeException("No Data Found")); |
| 67 | + } |
| 68 | +} |
0 commit comments