简化开关语句以避免代码重复
我有以下代码:(
String fullName = "";
switch(name) {
case "name1":
fullName = String.format("%s %s", name, "surname1");
break;
case "name2":
fullName = String.format("%s %s", name, "surname2");
break;
case "name3":
fullName = String.format("%s %s", name, "surname3");
break;
...
}
案例后有一个断点,我只是在这里写的),
所以这是一个问题:
有16个不同的案例语句都具有完全相同的代码.format()。
有什么方法可以简化此代码?
注意:Java 8是必须的
I have the following code:
String fullName = "";
switch(name) {
case "name1":
fullName = String.format("%s %s", name, "surname1");
break;
case "name2":
fullName = String.format("%s %s", name, "surname2");
break;
case "name3":
fullName = String.format("%s %s", name, "surname3");
break;
...
}
(there's a break statement after the cases, I just haven't written it here)
So here's the problem:
There's 16 different case statements all having the exact same code, except for the argument to String.format()
.
Is there any way I can simplify this code?
Note: Java 8 is a must
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,如果您的所有情况都具有确切的形式,那么您可以简单地做类似的事情:
或使用
MAP
查找值:Well, if all of your cases have that exact form, then you could simply do something like this:
Or use a
Map
to look up the value:地图
在其他地方概述的方法可能是Java 8的最佳方法,但请注意,在Java 14开始,您可以使用Switch表达式:The
Map
approach outlined elsewhere is probably your best best for Java 8, but note that as of Java 14, you can use a switch expression: