251.
instance that returns an Exception.
The following code
demonstrates this:
Optional
strOptional2 = Optional.empty();
String strValue2 = strOptional1.orElseThrow(()–> new
IllegalArgumentException());
Here, since strOptional2 is an empty Optional, the
orElseThrow() method throws an
IllegalArgumentException
What will be the output of the following code snippet?
Optional opInt1 = Optional.of(200); //Line 1
Optional opInt2 = opInt.filter(num–> num >
100); //Line 2
System.out.println(opInt2.get()); //Line 3
Answer:
The Optional class has a method called filter() which is used
in the code snippet above. The filter()method accepts as
Predicate and applies the Predicate to the value in the
Optional if present. If the condition in the Predicate is satisfied,
it returns the value in the Optional, otherwise it returns an empty
Optional. In this case, Line 1 creates an Integer Optional with the
value 200. Line 2 invokes the filter() method with a
Predicate that checks if the value in the Optional is greater
than 100. Since this is true, the filter() method returns an
Optional with the value 100 which is assigned to opInt2. So, the
get() method returns this value.
So, this code prints the following output: