|
| 1 | +# Optional class 📚 |
| 2 | +The `Optional` class was introduced in Java 8 to address the problem of null references. It provides a container object that may or may not contain a non-null value. This can be useful for methods that may or may not return a value or when dealing with potentially null values returned from external sources. |
| 3 | + |
| 4 | +## Introduction |
| 5 | + |
| 6 | +The `Optional` class is part of the `java.util` package and provides methods for working with potentially null values without encountering NullPointerExceptions. |
| 7 | + |
| 8 | +## Usage |
| 9 | + |
| 10 | +### Creating Optional Objects |
| 11 | + |
| 12 | +You can create an `Optional` object using the static `of()` method, which requires a non-null value. Alternatively, you can use `ofNullable()` if the value might be null. |
| 13 | + |
| 14 | +```java |
| 15 | +import java.util.Optional; |
| 16 | + |
| 17 | +Optional<String> nonEmpty = Optional.of("Hello"); |
| 18 | +Optional<String> empty = Optional.empty(); |
| 19 | +Optional<String> nullable = Optional.ofNullable(null); |
| 20 | +``` |
| 21 | +### Accessing Values |
| 22 | +You can retrieve the contained value using the get() method, but it's recommended to use methods like orElse() or orElseGet() to provide a default value if the optional is empty. |
| 23 | + |
| 24 | +```java |
| 25 | +String value = nonEmpty.get(); // "Hello" |
| 26 | +String defaultVal = empty.orElse("Default Value"); |
| 27 | +String defaultValSupplier = empty.orElseGet(() -> "Default Value from Supplier"); |
| 28 | +``` |
| 29 | +### Handling Absent Values |
| 30 | +To perform an action only if a value is present, you can use the ifPresent() method. |
| 31 | + |
| 32 | +```java |
| 33 | +nonEmpty.ifPresent(val -> System.out.println("Value is present: " + val)); |
| 34 | +``` |
| 35 | +### Best Practices |
| 36 | +Avoid using `get()` method directly, prefer `orElse()` or `orElseGet()` to handle absent values safely. |
| 37 | +Use `isPresent()` or `isEmpty()` to check if a value is present or absent. |
| 38 | +Be cautious when using `orElseThrow()` as it may introduce unnecessary complexity. |
| 39 | +### Examples 💡 |
| 40 | +Here's a simple example demonstrating the usage of Optional: |
| 41 | + |
| 42 | +```java |
| 43 | +import java.util.Optional; |
| 44 | + |
| 45 | +public class OptionalExample { |
| 46 | + public static void main(String[] args) { |
| 47 | + Optional<String> optional = Optional.of("Hello"); |
| 48 | + |
| 49 | + // Printing value if present |
| 50 | + optional.ifPresent(val -> System.out.println("Value is present: " + val)); |
| 51 | + |
| 52 | + // Using orElse to provide default value |
| 53 | + String value = optional.orElse("Default Value"); |
| 54 | + System.out.println("Value: " + value); |
| 55 | + |
| 56 | + // Using orElseThrow to throw exception if value is absent |
| 57 | + String val = optional.orElseThrow(() -> new IllegalArgumentException("Value is absent")); |
| 58 | + System.out.println("Value: " + val); |
| 59 | + } |
| 60 | +} |
| 61 | +``` |
| 62 | +### Conclusion 🎉 |
| 63 | +The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of `NullPointerExceptions` and making code more readable and robust. |
| 64 | + |
| 65 | +### ifPresent() Method |
| 66 | +The `ifPresent()` method takes a consumer function as an argument and executes it if a value is present. |
| 67 | + |
| 68 | +```java |
| 69 | +optional.ifPresent(val -> System.out.println("Value is present: " + val)); |
| 70 | +``` |
| 71 | +### ifPresentOrElse() Method |
| 72 | +Introduced in Java 9, the `ifPresentOrElse()` method executes one of two given actions, depending on whether a value is present or not. |
| 73 | + |
| 74 | +```java |
| 75 | +optional.ifPresentOrElse( |
| 76 | + val -> System.out.println("Value is present: " + val), |
| 77 | + () -> System.out.println("Value is absent") |
| 78 | +); |
| 79 | +``` |
| 80 | +### orElse() Method |
| 81 | +The `orElse()` method returns the value if present, otherwise returns the specified default value. |
| 82 | + |
| 83 | +```java |
| 84 | +String value = optional.orElse("Default Value"); |
| 85 | +``` |
| 86 | +### orElseGet() Method |
| 87 | +The `orElseGet()` method is similar to orElse(), but instead of a default value, it accepts a Supplier that provides the default value. |
| 88 | + |
| 89 | +```java |
| 90 | +String defaultValSupplier = empty.orElseGet(() -> "Default Value from Supplier"); |
| 91 | +``` |
| 92 | +### Best Practices |
| 93 | +- Avoid using `get()` method directly, prefer `orElse()` or `orElseGet()` to handle absent values safely. |
| 94 | +- Use `isPresent()` or `isEmpty()` to check if a value is present or absent. |
| 95 | +- Be cautious when using `orElseThrow()` as it may introduce unnecessary complexity. |
| 96 | +### Examples 💡 |
| 97 | +Here's a simple example demonstrating the usage of Optional: |
| 98 | + |
| 99 | +```java |
| 100 | +import java.util.Optional; |
| 101 | + |
| 102 | +public class OptionalExample { |
| 103 | + public static void main(String[] args) { |
| 104 | + Optional<String> optional = Optional.of("Hello"); |
| 105 | + |
| 106 | + // Printing value if present |
| 107 | + optional.ifPresent(val -> System.out.println("Value is present: " + val)); |
| 108 | + |
| 109 | + // Using orElse to provide default value |
| 110 | + String value = optional.orElse("Default Value"); |
| 111 | + System.out.println("Value: " + value); |
| 112 | + |
| 113 | + // Using orElseThrow to throw exception if value is absent |
| 114 | + String val = optional.orElseThrow(() -> new IllegalArgumentException("Value is absent")); |
| 115 | + System.out.println("Value: " + val); |
| 116 | + } |
| 117 | +} |
| 118 | +``` |
| 119 | +### Conclusion 🎉 |
| 120 | +The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of `NullPointerExceptions` and making code more readable and robust. |
| 121 | + |
| 122 | +### orElseThrow() Method |
| 123 | +The `orElseThrow()` method returns the value if present, otherwise throws an exception provided by the Supplier. |
| 124 | + |
| 125 | +```java |
| 126 | +String value = optional.orElseThrow(() -> new NoSuchElementException("Value is absent")); |
| 127 | +``` |
| 128 | +### map() Method |
| 129 | +The `map()` method applies a given function to the value if present and returns an Optional describing the result, or an empty Optional if the value is absent. |
| 130 | + |
| 131 | +```java |
| 132 | +Optional<Integer> lengthOptional = optional.map(String::length); |
| 133 | +``` |
| 134 | +### filter() Method |
| 135 | +The `filter()` method returns an Optional describing the value if a predicate is true, otherwise returns an empty Optional. |
| 136 | + |
| 137 | +```java |
| 138 | +Optional<String> filteredOptional = optional.filter(val -> val.startsWith("H")); |
| 139 | +``` |
| 140 | +### Best Practices |
| 141 | +- Avoid using `get()` method directly, prefer `orElse() or orElseGet() to handle absent values safely. |
| 142 | +- Use `isPresent()` or `isEmpty()` to check if a value is present or absent. |
| 143 | +- Be cautious when using orElseThrow() as it may introduce unnecessary complexity. |
| 144 | +### Examples 💡 |
| 145 | +Here's a simple example demonstrating the usage of Optional: |
| 146 | + |
| 147 | +```java |
| 148 | +import java.util.Optional; |
| 149 | + |
| 150 | +public class OptionalExample { |
| 151 | + public static void main(String[] args) { |
| 152 | + Optional<String> optional = Optional.of("Hello"); |
| 153 | + |
| 154 | + // Printing value if present |
| 155 | + optional.ifPresent(val -> System.out.println("Value is present: " + val)); |
| 156 | + |
| 157 | + // Using orElse to provide default value |
| 158 | + String value = optional.orElse("Default Value"); |
| 159 | + System.out.println("Value: " + value); |
| 160 | + |
| 161 | + // Using orElseThrow to throw exception if value is absent |
| 162 | + String val = optional.orElseThrow(() -> new IllegalArgumentException("Value is absent")); |
| 163 | + System.out.println("Value: " + val); |
| 164 | + } |
| 165 | +} |
| 166 | +``` |
| 167 | +### Conclusion 🎉 |
| 168 | +The Optional class provides a concise and safe way to handle potentially null values in Java, reducing the risk of NullPointerExceptions and making code more readable and robust. |
| 169 | +### Quick tip to filter Null elements with Stream API |
| 170 | +You can filter out null elements from a Stream using the `filter()` method along with a null-check condition. Here's a quick tip using the Stream API: |
| 171 | + |
| 172 | +```java |
| 173 | +import java.util.stream.Stream; |
| 174 | +import java.util.List; |
| 175 | +import java.util.Objects; |
| 176 | + |
| 177 | +public class Main { |
| 178 | + public static void main(String[] args) { |
| 179 | + List<String> listWithNulls = List.of("a", null, "b", null, "c"); |
| 180 | + |
| 181 | + // Filter out null elements using Stream API |
| 182 | + List<String> listWithoutNulls = listWithNulls.stream() |
| 183 | + .filter(Objects::nonNull) |
| 184 | + .toList(); |
| 185 | + |
| 186 | + // Print the list without null elements |
| 187 | + System.out.println("List without nulls: " + listWithoutNulls); |
| 188 | + } |
| 189 | +} |
| 190 | +``` |
| 191 | +In this example: |
| 192 | + |
| 193 | +- We have a list `listWithNulls` containing some elements along with null values. |
| 194 | +- We use the `stream()` method to convert the list into a Stream. |
| 195 | +- We apply the `filter()` method with a predicate Objects::nonNull to exclude null elements. |
| 196 | +- Finally, we collect the filtered elements into a new list using the `toList()` method introduced in Java 16. |
| 197 | +- This results in a new list `listWithoutNulls` containing only non-null elements. |
0 commit comments