Reputation: 1133
I am seeing if there is a better/nicer way of writing a long if statement using multiple ||
operators.
After looking online I see a lot of examples using conditional binomial operator. Is there a way this can be used when checking if a string equals a word?
The examples online follow this structure:
int price = condition?80:100;
Here is the function:
public boolean validateLetters(String word) {
if (word.equals("apple") || word.equals("excel") || word.equals("intern")
|| word.equals("orange") || word.equals("car")) {
return true;
}
return false;
}
The function checks to see the parameter word matches one of the following.
Is there a nicer or more efficient way I could write it?
Upvotes: 11
Views: 1397
Reputation: 23
We can achieve this in regex.
public boolean validateLetters(String word) {
if (word.matches("apple|excel|intern|orange|car")) {
return true;
}
return false;
}
Upvotes: 1
Reputation: 50061
if (condition) {
return true;
}
return false;
Can always be shortened to:
return condition;
Upvotes: 3
Reputation: 2806
You can use some sort of collection as it will make code more readable:
// Use a HashSet for performance
Set<String> values = new HashSet<String>(Arrays.asList("apple", "excel", "intern", "orange", "car"));
// In your method:
return values.contains(word);
A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.
You can also try this:
public boolean validateLetters(String word) {
switch(word) {
case "apple":
case "excel":
case "intern":
case "orange":
case "car":
return true;
default:
return false;
}
}
Upvotes: 3
Reputation: 308249
The simplest way for this specific check is to put all relevant words into a Set
and use contains
:
private static final Set<String> VALID_WORDS = Set.of("apple", "excel", "intern", "orange", "car");
public boolean validateLetters(String word) {
return VALID_WORDS.contains(word);
}
Generally speaking typing out a list of very similar checks combined in some way is an indication that you should refactor your code in some way.
Upvotes: 20