Simplify several boolean conditions java [duplicate]
-
21-12-2019 - |
Question
how would you simplify all these conditions?
String s = "The wold is big"
if(s.contains("is") || s.contains("are") || s.contains("was") || s.contains("were"))
{
return s;
}
Since I have to check several cases like those, is there a way to simplify all those conditions?
Solution
I would write a utility method for that:
public static boolean containsAny(String s, String... words) {
for (String word : words) {
if (s.contains(word))
return true;
}
return false;
}
And now:
if (containsAny(s, "is", "are", "was", "were")) {...}
Java 8 alternative:
if (Arrays.asList("is", "are", "was", "were").stream().anyMatch(s::contains)) {...}
OTHER TIPS
You can use regex for this using the matches
method of the String
sample:
String s = "The wold is big";
if (s.matches("(.*)(is|are|was|were)(.*)")) {
System.out.println("lawl");
}
There is not realy a quicker way to do it. Only if you have a lot of them it would be cleaner to put them in an array and walk over the array.
Also answered here: Test if a string contains any of the strings from an array
You can pass an array of value to check :
public boolean Contains(String[] list, String elem) {
for (String s: list){
if(elem.contains(s)) {
return true;
}
}
return false;
}
String s = "The wold is big"
String[] conditions = {"is","are","was","were"};
if(Contains(conditions,s))
{
return s;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow