您可以通过使用 Java 8 Optional.map() 和 Optional.orElseGet() 方法来避免 if 语句。检查以下示例:
import java.util.Optional;
import java.util.function.Consumer;
final class OptionalTestMain {
public static void main(String[] args) {
check("test", str -> {
System.out.println("Yay, string is not null!");
System.out.println("It's: " + str);
}, () -> {
System.out.println("Crap, string is a null...");
System.out.println("There is nothing for me to do.");
});
check(null, str -> {
System.out.println("Yay, string is not null!");
System.out.println("It's: " + str);
}, () -> {
System.out.println("Crap, string is a null...");
System.out.println("There is nothing for me to do.");
});
}
static void check(String str, Consumer<String> ifPresent, Runnable ifNotPresent) {
Optional.ofNullable(str)
.map(s -> { ifPresent.accept(s); return s; })
.orElseGet(() -> { ifNotPresent.run(); return null; });
}
}
它将产生以下输出:
Yay, string is not null!
It's: test
Crap, string is a null...
There is nothing for me to do.
方法 check 需要 3 个参数:
- 一个字符串(可能是
null)
- 一个
Consumer lambda 表达式,它对该值执行某些操作并且不会改变输入值。
- 当输入
String 是null 时,一个没有参数的Runnable lambda 可以做某事。
当然你可以很容易地修改下面的方法,然后利用Optional类的全部潜力,例如:
static String checkAndReturn(String str, Function<String, String> ifPresent, Supplier<String> ifNotPresent) {
return Optional.ofNullable(str)
.map(ifPresent)
.orElseGet(ifNotPresent);
}
然后:
System.out.println(checkAndReturn("test", String::toUpperCase, () -> "no value"));
System.out.println(checkAndReturn(null, String::toUpperCase, () -> "no value"));
将产生以下输出:
TEST
no value
希望对你有帮助。