java - 如何将充满 if 语句的 for 循环更改为更优雅/高效的代码?

这是我的字符串:

String field = "first=true, second=true"

我的方法对这个字符串进行操作并识别它是否包含 first=second= 子字符串,如果是 - 基于它调用其他方法之后的真/假。不过,第一个和第二个子串可能是可选的。这是我到目前为止:
void method(String field) {

      String[] splittedField = field.split(", ");
      for (String substring : splittedField) {
          if (substring.contains("first") {
              if (substring.contains("true") {
                  otherMethod("first", "true");
              } else if (substring.contains("false") {
                  otherMethod("first", "false");
              }
          } else if (substring.contains("second") {
              if (substring.contains("true") {
                  otherMethod("second", "true");
              } else if (substring.contains("false") {
                  otherMethod("second", "false");
              }
          }
      }

}

但也许有更好/更有效(和优雅?)的方法来解决这个案例?

最佳答案

考虑:

if (substring.contains("first") {
    if (substring.contains("true") {
        otherMethod("first", "true");
    } else if (substring.contains("false") {
        otherMethod("first", "false");
    }
 } 

上面的 if 可以编码为:
if (substring.contains("first") {
    String[] valueString = substring.split("=");            
    otherMethod("first", valueString[1]);
 }

https://stackoverflow.com/questions/60564862/

相关文章:

electron - 如何将在 Electron 上开发的桌面应用程序打包成.exe?

intellij-idea - IdeaVim:如何在不使用箭头键的情况下循环浏览列表项?

prolog - Prolog数据库的Web访问

r - 如何创建一个因子但保留基础值,而不仅仅是整数代码?

c - 我无法理解打印第一个八个数组元素的数组的输出

object-detection - 使用 >450K 个实例训练 Dlib 对象检测

vba - UDT 能否以任何方式用作方法参数?

java - 这个While 循环可以简化吗?

java - 在NIFI中创建自定义 Controller 服务时无法生成扩展的文档

java - Java 中的静态方法调用是如何工作的?