OptionalofNullableifPresent
The method Optional.ofNullable().ifPresent() is a part of the Optional class in Java.
The ofNullable() method is used to create an Optional object that may contain a non-null value or may be empty. It takes a parameter and returns an Optional object that wraps the parameter value if it is not null, or an empty Optional if the parameter value is null.
The ifPresent() method is used to perform an action on the value contained in the Optional object, if it is present. It takes a Consumer functional interface as a parameter, which specifies the action to be performed on the value. If the Optional object is not empty, the Consumer action is executed with the value as the input. If the Optional object is empty, the Consumer action is not executed.
Here's an example usage of Optional.ofNullable().ifPresent():
String name = "John Doe";
Optional<String> optionalName = Optional.ofNullable(name);
optionalName.ifPresent(n -> System.out.println("Name: " + n));
In this example, the optionalName object is created using Optional.ofNullable() with the name variable. Since name is not null, the optionalName object will contain the value "John Doe". The ifPresent() method is then called on the optionalName object with a Consumer action that prints the name. Since the optionalName object is not empty, the Consumer action is executed and the name "John Doe" is printed
原文地址: https://www.cveoy.top/t/topic/hZxE 著作权归作者所有。请勿转载和采集!