if (someString.equals('a') || someString.equals('b') || someString.equals('c') || someString.equals('d'))
How to shorten this syntax do not duplicate the equals ?
if (someString.equals('a') || someString.equals('b') || someString.equals('c') || someString.equals('d'))
How to shorten this syntax do not duplicate the equals ?
Regular expressions (please note it is a lot slower approach than your original one):
if (someString.matches("[abcd]")
Streams:
if (Arrays.stream(new String[] { "a", "b", "c", "d"}).anyMatch(input::equals))
In your answer it seems like you are trying to compare strings. In this case, I would use array syntax like this:
final String[] arr = {"a", "b", "c", "d"};
if(Arrays.asList(arr).contains("a")){
// Do Stuff
}
If you are only looking to compare single characters, @AdamSiemion's answer using Regex is spot-on.
If the goal is just clarity and brevity, you could always look at the character's ASCII value.
char c = someString.charAt(0);
if (c >= 'a' && c <= 'd'){
// do whatever
}
To understand this, you have to understand that a String is composed of a series of characters stored in an array. (It gets more complicated, of course, but that's a good starting point.)
Each one of these characters is ultimately coded as a number. The computer basically has a pre-built lookup table, where certain numbers reference certain characters. In that character table, the numbers for 'a'
, 'b'
, 'c'
(etc) are next to each other, and rising by one each time.
It's also important to understand that when you use 'a'
, you are referencing the character. By contrast, when you use "a"
, you are referencing a String. Strings can't be compared with >
, <
, or ==
, but characters can. So, by extracting the first character of the String, you are permitting yourself to check numerical ranges