[英]What is the better way for if condition with multiple OR in java? Java8 is preferable
How do I do it in a better way?我如何以更好的方式做到这一点? I prefer java8 syntax.
我更喜欢 java8 语法。
These boolean conditions could grow.这些布尔条件可能会增长。
boolean imageType = filetype.startsWith("image");
boolean videoType = filetype.startsWith("video");
boolean archiveType = filetype.contains("archive");
boolean jarType = filetype.contains("java-archive");
boolean audioType = filetype.startsWith("audio");
boolean zipType = filetype.contains("zip");
boolean xTarType = filetype.contains("x-tar");
boolean rarType = filetype.contains("rar");
if(!(imageType || videoType || archiveType || jarType || audioType || zipType || xTarType)) {
//doSomething
}
A more object oriented approach could also be used to give you a little bit more information about the file type.也可以使用更面向对象的方法来为您提供有关文件类型的更多信息。 I can imagine it being useful later on in your program.
我可以想象它稍后在您的程序中很有用。
You could do something like declare all your file types in an Enum
:您可以执行类似在
Enum
声明所有文件类型的操作:
public enum FileType {
IMAGE("a"),
VIDEO("b"),
ARCHIVE("c"),
JAR("d"),
AUDIO("e"),
ZIP("f"),
XTAR("g");
private String str;
FileType(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public static FileType getFileTypeForStr(String str) {
for (FileType fileType : FileType.values()) {
if (fileType.getStr().equalsIgnoreCase(str)) {
return fileType;
}
}
return null;
}
}
Then, in your function, you could replace all your Booleans
with a check to see if your input String1
is an included file type:然后,在您的函数中,您可以用检查替换所有
Booleans
值,以查看您的输入String1
是否为包含文件类型:
FileType fileType = FileType.getFileTypeForStr(String1); //And String2, String3, String4...
if (fileType != null) {
System.out.printf("File type found of type %s", fileType.name());
} else {
System.out.printf("No file type found for input %s", String1);
}
Since you have 7 different Strings to check, you could add a simple check to see if all the String1
variables are a match:由于您有 7 个不同的字符串要检查,您可以添加一个简单的检查以查看所有
String1
变量是否匹配:
boolean isNotFileType = Stream
.of(String1, String2, String3, String4, String5, String6, String7)
.map(FileType::getFileTypeForStr)
.anyMatch(Objects::isNull);
1) Regroup your conditions in Predicate s. 1) 在Predicate s 中重新组合您的条件。 Take the case of an Enum:
以枚举为例:
public enum PredicateEnum {
IMAGE (filetype -> filetype.startsWith("image")),
VIDEO (filetype -> filetype.startsWith("video")),
ARCHIVE (filetype -> filetype.contains("archive")),
JAR (filetype -> filetype.contains("java-archive")),
AUDIO (filetype -> filetype.startsWith("audio")),
ZIP (filetype -> filetype.contains("zip")),
X_TAR (filetype -> filetype.contains("x-tar")),
RAR (filetype -> filetype.contains("rar"));
private Predicate<String> predicate;
PredicateEnum(Predicate<String> predicate) {
this.predicate = predicate;
}
public Predicate<String> getPredicate() {
return predicate;
}
}
2) Use Stream#reduce and Predicate#or to create a single Predicate which is the result of all your predicates connected by logic OR operators: 2) 使用Stream#reduce和Predicate#or创建一个 Predicate,它是由逻辑 OR 运算符连接的所有谓词的结果:
Predicate<String> predicateOr = Stream.of(PredicateEnum.values())
.map(PredicateEnum::getPredicate)
.reduce(Predicate::or)
.orElse(s -> false);
System.out.println("image.png: " + predicateOr.test("image.png"));
System.out.println("my-archive.txt: " + predicateOr.test("my-archive.txt"));
System.out.println("foo : " + predicateOr.test("foo"));
3) Use the result of Predicate#test in your if
statement. 3) 在
if
语句中使用Predicate#test的结果。 For example, the code above prints out:例如,上面的代码打印出:
image.png: true
my-archive.txt: true
foo : false
Here are a couple of ways to make this more "scaleable".这里有几种方法可以使这个更“可扩展”。
Use a regex:使用正则表达式:
Pattern p = Pattern.compile("^video|^audio|^image|zip|rar|java-archive|x-tar"); if (!p.matcher(filetype).find()) { // do stuff }
Use arrays or lists.使用数组或列表。 For example:
例如:
String[] prefixes = new String[]{"video", "audio", "images"}; String[] contains = new String[]{"zip", "rar", "x-tar", "jar-archive"}; boolean match = false; for (String p : prefixes) { if (filetype.startsWith(p)) { match = true; } } ... if (!match) { // do stuff }
Clearly, the regex approach is more concise, but the array approach is probably more efficient (if that matters!).显然,正则表达式方法更简洁,但数组方法可能更有效(如果这很重要!)。 It depends on how the regex engine copes with a regex with lots of alternatives.
这取决于正则表达式引擎如何处理具有许多替代方案的正则表达式。
Both approaches will scale;这两种方法都会扩展; eg by updating the regex, or by adding strings to the arrays.
例如通过更新正则表达式,或通过向数组添加字符串。
In both cases, you could easily load the relevant criteria from a properties file or similar ... and avoid making code changes.在这两种情况下,您都可以轻松地从属性文件或类似文件中加载相关条件……并避免更改代码。
I'm not convinced the Java 8 lambdas and streams are a good fit for this problem.我不相信 Java 8 lambdas 和流很适合解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.