Java中基于String.contains的if-else-if语句重构方案咨询
重构Java中
if-else-if string.contains("X")语句的方案 一、解决switch case实现的问题
Java标准switch语句(Java 17之前)要求表达式结果为可枚举类型(如String、枚举、基本类型等),无法直接使用布尔条件。要适配switch,可先提取匹配的关键词,再基于关键词做判断:
方案1:先匹配关键词再用switch
public String question(String sentence) { String matchedKeyword = null; // 按原if-else的优先级顺序检查关键词 if (sentence.contains("eat")) matchedKeyword = "eat"; else if (sentence.contains("drink")) matchedKeyword = "drink"; else if (sentence.contains("drive")) matchedKeyword = "drive"; else if (sentence.contains("travel")) matchedKeyword = "travel"; // ...其他关键词检查 switch (matchedKeyword) { case "eat": return getFoodFromSentence(sentence); case "drink": return getBeverageFromSentence(sentence); case "drive": return getVehicleFromSentence(sentence); case "travel": return getDestinationFromSentence(sentence); // ...其他case分支 default: return "sentence with unknown verb"; } }
方案2:Java 17+模式匹配switch(更简洁)
如果使用Java 17及以上版本,可结合流找到第一个匹配的关键词,再用switch表达式处理:
import java.util.List; public String question(String sentence) { return List.of("eat", "drink", "drive", "travel") .stream() .filter(sentence::contains) .findFirst() .map(keyword -> switch (keyword) { case "eat" -> getFoodFromSentence(sentence); case "drink" -> getBeverageFromSentence(sentence); case "drive" -> getVehicleFromSentence(sentence); case "travel" -> getDestinationFromSentence(sentence); // ...其他case分支 default -> "sentence with unknown verb"; }) .orElse("sentence with unknown verb"); }
二、解决Map实现的问题
你之前用Predicate<String>作为Map键的方式不可行,因为Predicate的equals/hashCode基于对象引用,无法通过动态判断匹配对应键。正确做法是将关键词作为键,遍历Map找到第一个匹配项:
优化后的Map方案
import java.util.Map; import java.util.function.Function; public String question(String sentence) { // 键为关键词,值为对应的处理函数 Map<String, Function<String, String>> handlerMap = Map.of( "eat", this::getFoodFromSentence, "drink", this::getBeverageFromSentence, "drive", this::getVehicleFromSentence, "travel", this::getDestinationFromSentence // ...其他键值对 ); // 按插入顺序遍历Map,保证和原if-else优先级一致 for (Map.Entry<String, Function<String, String>> entry : handlerMap.entrySet()) { if (sentence.contains(entry.getKey())) { return entry.getValue().apply(sentence); } } return "sentence with unknown verb"; }
注意:Java 9+的
Map.of()创建的是有序Map,遍历顺序与插入顺序一致,能保留原逻辑的优先级;若使用普通HashMap,顺序不固定可能破坏原有判断逻辑。
三、其他重构技巧
1. 枚举封装策略
将关键词与处理逻辑封装到枚举中,扩展性更强:
enum VerbHandler { EAT("eat", this::getFoodFromSentence), DRINK("drink", this::getBeverageFromSentence), DRIVE("drive", this::getVehicleFromSentence), TRAVEL("travel", this::getDestinationFromSentence); // ...其他枚举项 private final String keyword; private final Function<String, String> handler; VerbHandler(String keyword, Function<String, String> handler) { this.keyword = keyword; this.handler = handler; } public String handle(String sentence) { return handler.apply(sentence); } public static VerbHandler findMatch(String sentence) { for (VerbHandler handler : values()) { if (sentence.contains(handler.keyword)) { return handler; } } return null; } } // 使用枚举 public String question(String sentence) { VerbHandler handler = VerbHandler.findMatch(sentence); return handler != null ? handler.handle(sentence) : "sentence with unknown verb"; }
2. 策略模式+列表
若不需要枚举,可自定义类存储关键词与处理函数,放到列表中管理:
import java.util.List; import java.util.function.Function; class VerbStrategy { private final String keyword; private final Function<String, String> handler; public VerbStrategy(String keyword, Function<String, String> handler) { this.keyword = keyword; this.handler = handler; } public boolean matches(String sentence) { return sentence.contains(keyword); } public String handle(String sentence) { return handler.apply(sentence); } } // 使用策略列表 public String question(String sentence) { List<VerbStrategy> strategies = List.of( new VerbStrategy("eat", this::getFoodFromSentence), new VerbStrategy("drink", this::getBeverageFromSentence), new VerbStrategy("drive", this::getVehicleFromSentence), new VerbStrategy("travel", this::getDestinationFromSentence) // ...其他策略 ); return strategies.stream() .filter(VerbStrategy::matches) .findFirst() .map(s -> s.handle(sentence)) .orElse("sentence with unknown verb"); }
内容的提问来源于stack exchange,提问作者PatPanda
相关产品推荐
相关产品推荐

