在java中跟随if-else梯的更好的替代方法是什么?

时间:2016-04-15 09:29:48

标签: java string if-statement optimization

情况:我正在检查文件名,文件名存储在名为String的{​​{1}}变量中,并且根据我在str语句中检查的条件设置名为if的变量的值。

mailType

问题:有没有更好的方法在java中缩短我的代码并且对内存友好?

5 个答案:

答案 0 :(得分:20)

使用LinkedHashMap<String, String>

LinkedHashMap<String, String> mapping = new LinkedHashMap<>();
mapping.put("unsupported", "unsupported");
mapping.put("final_result", "final_result");
// ... etc

然后迭代地图,直到找到匹配的键:

for (Map.Entry<String, String> entry : mapping.entrySet()) {
  if (str.contains(entry.getKey()) {
    mailType = entry.getValue();
    break;
  }
}

这里的关键点是LinkedHashMap保留了插入顺序(与HashMap不同),因此您可以实际指定要测试匹配的顺序(其他地图实现也会这样做,例如Guava的ImmutableMap; LinkedHashMap只是您开箱即用的内容之一。)

如果你需要为外壳嵌套这个,你可以简单地应用相同的模式:

LinkedHashMap<String, LinkedHashMap<String, String>> outerMapping =
    new LinkedHashMap<>();
outerMapping.put("template", mapping);
outerMapping.put("properties", someOtherMapping);

然后以相同的方式迭代键:

for (Map.Entry<String, LinkedHashMap<String, String>> outerEntry : outerMapping.entrySet()) {
  if (str.contains(outerEntry.getKey()) {
    // Apply the iteration above, using outerEntry.getValue().
  }
}

答案 1 :(得分:2)

你说你发现Andy's answer(这就是我要做的)太复杂了。他的original comment建议else if可能适合您:

if (str.contains("template")) {
    if (str.contains("unsupported"))
        mailType = "unsupported";
    else if (str.contains("final_result"))
        mailType = "final_result";
    else if (str.contains("process_success"))
        mailType = "Process Success";
    else if (str.contains("receive"))
        mailType = "Receive";
    else if (str.contains("sen"))
        mailType = "sent";
    else if (str.contains("welcome"))
        mailType = "welcome";
    else if (str.contains("manual"))
        mailType = "Manual";
} else if (str.contains("properties")) {
    if (str.contains("unsupported"))
        mailType = "unsupported";
    else if (str.contains("final_result"))
        mailType = "final_result";
    else if (str.contains("process_success"))
        mailType = "Process Success";
    else if (str.contains("receive"))
        mailType = "Receive";
    else if (str.contains("sen"))
        mailType = "sent";
    else if (str.contains("welcome"))
        mailType = "welcome";
    else if (str.contains("manual"))
        mailType = "Manual";
}

或更好,一直使用{}:

if (str.contains("template")) {
    if (str.contains("unsupported")) {
        mailType = "unsupported";
    } else if (str.contains("final_result")) {
        mailType = "final_result";
    } else if (str.contains("process_success")) {
        mailType = "Process Success";
    } else if (str.contains("receive")) {
        mailType = "Receive";
    } else if (str.contains("sen")) {
        mailType = "sent";
    } else if (str.contains("welcome")) {
        mailType = "welcome";
    } else if (str.contains("manual")) {
        mailType = "Manual";
    }
} else if (str.contains("properties")) {
    if (str.contains("unsupported")) {
        mailType = "unsupported";
    } else if (str.contains("final_result")) { 
        mailType = "final_result";
    } else if (str.contains("process_success")) {
        mailType = "Process Success";
    } else if (str.contains("receive")) {
        mailType = "Receive";
    } else if (str.contains("sen")) {
        mailType = "sent";
    } else if (str.contains("welcome")) {
        mailType = "welcome";
    } else if (str.contains("manual")) { 
        mailType = "Manual";
    }
}

答案 2 :(得分:1)

试试这个

static String containsAndValue(Collection<String> collection, String oldValue, String... strings) {
    if (strings.length % 2 != 0)
        throw new IllegalArgumentException("strings");
    for (int i = 0; i < strings.length; i += 2)
        if (collection.contains(strings[i]))
            return strings[i + 1];
    return oldValue;
}

if (str.contains("template")) {
    mailType = containsAndValue(str, mailType,
        "unsupported", "unsupported",
        "final_result", "final_result",
        "process_success", "Process Success",
        "receive", "Receive",
        "sen", "sent",
        "welcome", "welcome",
        "manual", "Manual");
} else if (str.contains("properties")) {
    mailType = containsAndValue(str, mailType,
        "unsupported", "unsupported",
        "final_result", "final_result",
        "process_success", "Process Success",
        "receive", "Receive",
        "sen", "sent",
        "welcome", "welcome",
        "manual", "Manual");
}

答案 3 :(得分:1)

这不那么复杂吗?

public enum MailType {
    UNSUPPORTED("unsupported", "unsupported"),
    FINAL_RESULT("final_result", "final_result"),
    PROCESS_SUCCESS("process_success", "Process Success"),
    RECEIVE("receive", "Receive"),
    SENT("sen", "sent"),
    WELCOME("welcome", "welcome"),
    MANUAL("manual", "Manual");

    private final String query;
    private final String value;

    MailType(String query, String value) {
        this.query = query;
        this.value = value;
    }

    public static String find(String text){
        for(MailType mailType: values()){
            if(text.contains(mailType.query)) {
                return mailType.value;
            }
        }
        return null;
    }
}

并像这样使用它:

String mailType = MailType.find(str);

答案 4 :(得分:0)

首先,如果您使用byte[] bytes = Encoding.UTF8.GetBytes(publicKeyString); IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKeyString); AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); CryptographicKey publicKey = provider.ImportPublicKey(keyBuffer,CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);` 而非简单else if,则缩进的次数会减少。

else

在您的特定情况下,我建议尝试使用正则表达式来简化您的工作:

if(str.contains("unsupported"))
          mailType="unsupported";      
else if(str.contains("final_result"))                
          mailType="final_result";            
else if(str.contains("process_success"))
          mailType="Process Success"; 
else if(str.contains("receive"))                         
          mailType="Receive";                         
else if(str.contains("sen"))
          mailType="sent"; 
else if(str.contains("welcome"))
          mailType="welcome";
else if(str.contains("manual"))
          mailType="Manual";