To use Optional, wrap the type
Optional<String> opt1;
Same for homebrew class
testClass.java
public class testClass
{
private String no;
private BigDecimal val;
}
OPtional<testClass> opt2;
Use optional.of or optional.ofNullable to populate the optional type.
Optional<String> opt1 = Optional.of("test");
However, note that optional.of will cause an Exception if the argument is null.
Optional<String> opt1 = Optional.of(null);
Therefore, use optional.ofNullable.
Optional<String> opt1 = Optional.ofNullable("test");
Optional<String> opt2 = Optional.ofNullable(null);
testClass test = new testClass();
Optional<String> opt3 = Optional.ofNullable(test);
To retrieve the value, use: get: If null, Exception occurs orElse: Returns the variable value if null does not appear, or returns the argument of orElse if null orElseGet: If null does not appear, variable value, if null, return the result of supplier
String val1 = opt1.get();
String val2 = opt1.orElse("")
When retrieving a value from your own class, you can get the field using: map
String val1 = opt3.map(testClass::getNo).orElse("1");
String val2 = opt3.map(v -> v.getNo()).orElse("2");
Recommended Posts