Java 条件判断大全:从入门到黑科技(15 段代码,复制即用)
2026/5/26 1:07:14 网站建设 项目流程

一、基础三件套(10 秒复习)
1. if-else
if (score >= 90) { /* 优秀逻辑 */ }
else if (score >= 60) { /* 合格逻辑 */ }
else { /* 不合格逻辑 */ }
牢记:永远加大括号;多分支用“早 return”消灭嵌套。

2. 三元运算符(一行 if)
String level = score > 90 ? "优秀" : "及格或不及格";
只写一层,嵌套过深立刻换回 if-else。

3. switch 表达式(JDK14+正式)
String level = switch (score / 10) {
case 9, 10 -> "优秀";
case 8 -> "良好";
default -> "及格或不及格";
};
无需 break,编译器自动检查完整性;提前返回用 yield。

二、流程控制黑科技
4. 标签跳出多层循环
OUTER: for (...) {
for (...) {
if (condition) break OUTER; // 跳出两层
}
}

5. 早 return 策略(干掉 else)
public String calc(int n) {
if (n > 100) return "超大";
if (n > 50) return "大";
return "标准"; // 无 else,左对齐
}

6. Map 函数式状态机(O(1)分支,热插拔)
Map<String, IntUnaryOperator> ops = Map.of(
"A", x -> x + 1,
"B", x -> x * 2,
"C", x -> x * x
);
int result = ops.getOrDefault(type, x -> 0).apply(num);
新增分支只扔 Map,不改旧代码。

三、设计模式级条件判断
7. 策略模式——消灭 if-else 森林
interface DiscountStrategy { BigDecimal apply(BigDecimal original); }
@Service
class VipStrategy implements DiscountStrategy {
public BigDecimal apply(BigDecimal o) {
return o.multiply(new BigDecimal("0.7"));
}
}
// Spring 自动注入 Map<String,DiscountStrategy>
DiscountStrategy strategy = strategyMap.get(userType);
BigDecimal finalPrice = strategy.apply(price);

8. 责任链模式——“条件过滤器”管道
Function<Req, Resp> chain =
validate.andThen(checkStock).andThen(deductBalance).andThen(createOrder);
Resp r = chain.apply(req);
每一环只关心自己的规则,失败抛异常,链条自动终止。

9. Optional 链式判断——层层 null 安全
String city = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.orElse("未知");
一行代码代替多层 if (xx != null) 嵌套。

四、性能/字节码级技巧
10. 表驱动替代长 switch——零分支,CPU 预测友好
static final int[] DAY_TABLE = {0, 1, 1, 1, 1, 1, 2, 2}; // 周一=0
int weekDay = DAY_TABLE[cal.get(Calendar.DAY_OF_WEEK)];

11. 位运算求 max——省一次分支
int max = a - ((a - b) & ((a - b) >> 31));
用符号位生成掩码,微基准快 3-5 ns。

12. 条件注入——AOP 把“if”切到运行时
@Around("@annotation(limit)")
public Object check(ProceedingJoinPoint p, Limit limit) {
if (!rateLimiter.tryAcquire()) throw new RuntimeException("限流");
return p.proceed();
}
业务代码 0 条件判断,由框架字节码注入。

五、思维导图(收藏版)
条件判断高阶
├─ 基础:if-else / 三元 / switch
├─ 流程:标签 break + 早 return + Map 状态机
├─ 模式:策略 + 责任链 + Optional 链
└─ 性能:表驱动 + 位运算 + AOP 注入

六、一句话总结
基础语法解决“有没有”,高阶技巧解决“好不好、快不快、爽不爽”。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询