Some previous post had optional.get() in them which is not a best practice if its not with Optional.isPresent(). better than isPresent is to use orElse(), orElseGet(), orElseThrow()
Transcribed from the original LinkedIn image post.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| import java.util.OptionalInt;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
class Day20 {
public static void main(String[] args) throws Exception {
int defaultNumber = Integer.MAX_VALUE;
IntSupplier intSupplier = () -> (int) (Math.random() * 100);
IntStream intStream = IntStream.range(0, 10);
OptionalInt maxValue = intStream
.filter(i -> i > 3)
.findAny();
// get value. if not present then get the default number
int maxValueOrElse = maxValue.orElse(defaultNumber);
// get value. if not present get free provided supplier
int maxValueOrElseGet = maxValue.orElseGet(intSupplier);
// get value. if not present throws an exception
int maxValueOrElseThrow = maxValue.orElseThrow(() -> new Exception("No value present"));
}
}
|
The original LinkedIn graphic is preserved below.
