简化/优化大量if ... else if ... else语句

时间:2020-08-03 03:22:16

标签: java performance if-statement optimization

基本上可以,我有一些使用contains()方法的代码来检测两个字符串中特定字符的存在。对于其他情况,this question是我遇到哪种问题的好资源(第三个解决方案也是我研究的问题)。无论如何,这是我的一些代码:

// code up here basically just concatenates different
// characters to Strings: stringX and stringY

if (stringX.contains("!\"#")) {
} else if (stringX.contains("$%&")) {
} else if (stringX.contains("\'()")) {
} else if (stringX.contains("!$\'")) {
} else if (stringX.contains("\"%(")) {
// literally 70+ more else-if statements
}

if (stringY.contains("!\"#")) {
} else if (stringY.contains("$%&")) {
} else if (stringY.contains("\'()")) {
} else if (stringY.contains("!$\'")) {
} else if (stringY.contains("\"%(")) {
// literally 70+ more else-if statements, all of which are
// exactly the same as those working with stringX
}

我对Java编程还是很陌生,所以我不确定该怎么做。也许这不是问题?另外,如果我不使用RegEx就可以解决这个问题,那将是更好的选择。目前我还不是很了解。但是,如果唯一合理的解决方案是利用它,那么我显然会这样做。

编辑:所有这些else-if语句中的代码根本不会有太大区别;基本上只是一个System.out.println(),其中包含一些有关stringX / stringY包含哪些字符的信息。

2 个答案:

答案 0 :(得分:3)

只需列出您的案子即可。然后使用java 8 stream filter

List<String> pattems = Arrays.asList("!\"#", "$%&", ...);
Optional<String> matched = pattems.stream().filter(p -> stringX.contains(p));
if(matched.isPresent()) {
   System.console().printf(matched.get())
}

java stream可以使您的表现slower但不会太大

答案 1 :(得分:3)

多次编写相同的代码应该立即触发头脑中的警钟,以将该代码移入功能,以便可以重复使用。

关于简化表达式,最好的方法可能是将要查找的模式存储为数组,并根据条件在数组上进行迭代。

private static final String[] patterns = new String[] {"!\"#", "$%&", "\'()", "!$\'", "\"%(", ...};

private static void findPatterns(String input) {
    for (String pattern : patterns) {
        if (input.contains(pattern) {
            System.out.println("Found pattern: " + pattern);
        }
    }
}

// Elsewhere...
findPatterns(stringX);
findPatterns(stringY);

此模式在功能和功能样式的语言中尤其常见。 Java 8流是一个很好的例子,因此您可以等效地

List<String> patterns = Arrays.asList("!\"#", "$%&", "\'()", "!$\'", "\"%(", ...);
patterns.stream()
    .filter(pattern -> stringX.contains(pattern))
    .forEach(pattern -> System.out.println("Found pattern: " + pattern));