Following is an example of writing less verbose and clean code for optional value comparison.
This code (isAbc2) avoids unnecessary IF condition.
The code sample also has a way to compare clean code and legacy code for a safety.
import java.util.Optional;
public class C1 {
public static void main(String[] arg) {
Optional val = Optional.of("abc");
Optional noval = Optional.empty();
Optional def = Optional.of("def");
System.out.println(isAbc1(val) == isAbc2(val));
System.out.println(isAbc1(noval) == isAbc2(noval));
System.out.println(isAbc1(def) == isAbc2(def));
}
private static boolean isAbc1(Optional op) {
if(op.isPresent()) {
return op.get().equals("abc");
}
return false;
}
// clean code
private static boolean isAbc2(Optional op) {
return op.map("abc"::equals).orElse(false);
}
}
The result of the above code in JDK 11.
true
true
true