forked from tugul/CoreJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAboutOptional.java
More file actions
94 lines (80 loc) · 4.2 KB
/
Copy pathAboutOptional.java
File metadata and controls
94 lines (80 loc) · 4.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package streams;
import java.time.LocalDate;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
/**
* - Optional
* final class in java.util package
* introduced in Java 8 to reduce null pointer exceptions
* container type wrapping a single primitive or object which might be absent or present
* more expressive than null, so supports functional programming style
*
* - Static methods to create Optional
* Optional<T> of - creates optional with given value. Can't create value from null, so ofNullable is safer
* Optional<T> ofNullable(T) - creates optional with given value. If the value is null, it creates Optional.empty()
* Optional<T> empty() - creates optional object with empty value in it
*
* - Caller of a method returning Optional
* recommended to call isPresent to check value is present or not before accessing value
* T get() - returns the wrapped value or throws NoSuchElementException if the value is empty/absent
* boolean isPresent() - check if value is present or not
* void ifPresent(Consumer<T>) - call Consumer parameter if value is present
*
* - To deal with absent case / if value in Optional is absent
* T orElse(T) - returns given parameter value
* T orElseGet(Supplier<T>) - returns result of Supplier
* T orElseThrow(Supplier<Throwable>) - throws exception
*
* - Primitive Optional classes with methods specific to their types
* OptionalInt - getAsInt(), orElse(int), orElseGet(IntSupplier)
* OptionalLong - getAsLong(), orElse(long), orElseGet(LongSupplier)
* OptionalDouble - getAsDouble(),orElse(double), orElseGet(DoubleSupplier)
*
*/
public class AboutOptional {
public static Optional<Double> findAverage(int... nums){
if (nums.length == 0)
return Optional.empty();
return Optional.of((double)IntStream.of(nums).sum() / nums.length);
}
public static void main(String[] args) {
// empty() - creates instance with empty value
Optional optionalEmpty = Optional.empty();
OptionalLong optionalLong = OptionalLong.empty();
// of(T) - creates instance with given value
Optional optionalDate = Optional.of(LocalDate.now());
OptionalInt optionalInt = OptionalInt.of(5);
OptionalDouble optionalDouble = OptionalDouble.of(.5);
// ofNullable(T) - equivalent to ternary operator and replace it
Object value = null;
Optional obj1 = (value== null) ? Optional.empty(): Optional.of(value);
Optional obj2 = Optional.ofNullable(value);
// System.out.println(Optional.of(null)); // throws NullPointerException
System.out.println(Optional.ofNullable(null)); // Optional.empty
System.out.println(findAverage(10, 30)); // Optional[20.0]
System.out.println(findAverage()); // Optional.empty
Double avg1 = findAverage(10, 20).get(); // 20.0
//Double avg2 = findAverage().get(); // throws NoSuchElementException
Double avg3 = findAverage().orElse(Double.NaN); // to avoid this exception thrown
// boolean isPresent()
// checks if has value or not
Optional<Double> emptyOptional = findAverage();
if (emptyOptional.isPresent())
System.out.println(emptyOptional.get()); // without check, it will throw NoSuchElementException
// void ifPresent(Consumer<T>)
// It runs Consumer logic if value is present, otherwise won't run
emptyOptional.ifPresent(System.out::println); // no output
Optional<Integer> add = Optional.of(2);
System.out.println(add); // Optional[2]
add.ifPresent(System.out::println); // 2
System.out.println(emptyOptional.orElse(null)); // null
System.out.println(emptyOptional.orElse(Double.NaN)); // Nan
System.out.println(emptyOptional.orElseGet(() -> Math.random())); // orElseGet takes double
System.out.println(emptyOptional.orElseThrow(() -> new IllegalStateException())); // using lambda
System.out.println(emptyOptional.orElseThrow(IllegalStateException::new)); // method reference
}
}