a.
b.
c.
249.
Optional.isEmpty– This creates an empty Optional, that
is an Optional without a value as shown below:
Optional
number = Optional.empty();
Optional.of– This creates an Optional with a particular
value as shown below:
Optional number = Optional.of(10); //creates
Optional with the value 10
Optional.ofNullable– This creates an Optional with
either a null or a non–null value as shown below:
Optional number = Optional.ofNullable(10);
//creates Optional with the value 10
It can also be used to create an Optional with a null value as
follows:
Optional number = Optional.ofNullable(null);
Explain the Optional.ifPresent method with a code
sample.
Answer:
The Optional.ifPresent method performs an operation on
the value in the Optional if it is present. The operation to be
performed is specified as a Consumer instance. If the Optional is
empty, it does not do anything. The following code demonstrates
this:
Optional strOptional = Optional.of(“Test”);
250.
strOptional.ifPresent(str–>
System.out.println(str.toUpperCase()));
This code creates an Optional strOptional corresponding to
the value
Test. The ifPresent method
is then invoked with a
lambda expression that converts the value in the Optional to
uppercase and prints it. So, this code prints the following output:
TEST
In case,
the input Optional is empty, the ifPresent() method
does not do anything.
Do'stlaringiz bilan baham: