- 包括有关您的目标的详细信息:
我想重构if-else-if string.contains("X")
Java 中的语句来切换大小写或 Map。
- 显示一些代码:
我有一段代码,非常简单,如下所示:
public String question(String sentence) {
if (sentence.contains("eat")) {
return getFoodFromSentence(sentence);
} else if (sentence.contains("drink")) {
return getBeverageFromSentence(sentence);
} else if (sentence.contains("drive")) {
return getVehicleFromSentence(sentence);
} else if (sentence.contains("travel")) {
return getDestinationFromSentence(sentence);
[...
many many other else if
...]
} else {
return "sentence with unknown verb";
}
}
private String getDestinationFromSentence(String sentence) {
return ""; //some complex code to extract some info from the sentence
}
private String getVehicleFromSentence(String sentence) {
return ""; //some complex code to extract some info from the sentence
}
[... all the other actual handling methods ]
我希望使用 switch case 来重构它:
- 描述一下我的尝试:
使用 switch case:
public String question(String sentence) {
switch (???) { //issue here, I am not able to come up with the expression
case (sentence.contains("eat")): // issue here, I am not able to have the cases representing the if
return getFoodFromSentence(sentence);
case (sentence.contains("drink")):
return getBeverageFromSentence(sentence);
case (sentence.contains("drive")):
return getVehicleFromSentence(sentence);
case (sentence.contains("travel")):
return getDestinationFromSentence(sentence);
[ ... the other case conditions ... ]
default:
return "sentence with unknown verb";
}
}
我也尝试使用 Map 模式,例如:
public String question(String sentence) {
Map<Predicate<String>, Function<String, String>> map =
Map.of(s -> s.contains("eat"), s -> getFoodFromSentence(s),
s -> s.contains("drink"), s -> getBeverageFromSentence(s),
s -> s.contains("drive"), s -> getVehicleFromSentence(s),
s -> s.contains("travel"), s -> getDestinationFromSentence(s));
return map.get(???).apply(sentence); // issue here, how to get the correct key of the map?
}
- 问题:
请问使用 switch case 的问题该如何解决?
或者也许如何解决地图问题?
还有其他技术可以重构这个吗 if-else-if string.contains("X")
?
对于基于地图的方法,您可以尝试以下方法:
case
语句可以使用when
关键字:与 tobias_k 的 map 方法类似的解决方案仅使用 LinkedHashMap 来保证顺序,并使用流和可选项来稍微提高可读性: