java如何简化if
简化 Java 中 if 语句的方法
使用三元运算符
三元运算符 (condition ? expr1 : expr2) 可以替代简单的 if-else 语句,使代码更简洁。
// 传统写法
if (score > 60) {
result = "Pass";
} else {
result = "Fail";
}
// 简化写法
result = score > 60 ? "Pass" : "Fail";
使用 Optional 处理空值Optional 可以避免显式的 if (obj != null) 检查,减少嵌套。

// 传统写法
if (user != null && user.getName() != null) {
name = user.getName();
} else {
name = "Unknown";
}
// 简化写法
name = Optional.ofNullable(user)
.map(User::getName)
.orElse("Unknown");
提前返回(Early Return)
通过提前返回减少嵌套层级,提升可读性。
// 传统嵌套写法
if (condition1) {
if (condition2) {
return value;
}
}
return null;
// 简化写法
if (!condition1) return null;
if (!condition2) return null;
return value;
使用 switch 表达式(Java 12+)
对于多条件分支,switch 表达式比 if-else 链更清晰。

// 传统写法
String status;
if (code == 1) {
status = "Pending";
} else if (code == 2) {
status = "Approved";
} else {
status = "Rejected";
}
// 简化写法(Java 12+)
status = switch (code) {
case 1 -> "Pending";
case 2 -> "Approved";
default -> "Rejected";
};
策略模式或枚举
将条件逻辑封装到策略类或枚举中,避免冗长的 if-else。
// 传统写法
if (type.equals("A")) {
processA();
} else if (type.equals("B")) {
processB();
}
// 简化写法(策略模式)
Map<String, Runnable> strategies = Map.of(
"A", this::processA,
"B", this::processB
);
strategies.getOrDefault(type, () -> {}).run();
使用 Stream API 过滤数据
对于集合的条件过滤,Stream API 比循环 + if 更简洁。
// 传统写法
List<String> filtered = new ArrayList<>();
for (String s : list) {
if (s.startsWith("A")) {
filtered.add(s);
}
}
// 简化写法
List<String> filtered = list.stream()
.filter(s -> s.startsWith("A"))
.toList();






