-1
if (someString.equals('a') || someString.equals('b') ||    someString.equals('c') || someString.equals('d'))

How to shorten this syntax do not duplicate the equals ?

Aniruddha K.M
  • 7,361
  • 3
  • 43
  • 52
Walter White
  • 976
  • 4
  • 12
  • 29
  • You could but the chars in an array and check for any matches. You could check the range, e.g., https://stackoverflow.com/q/33044520/438992. – Dave Newton Oct 23 '17 at 16:59
  • Is there some guarantee that `someString` will be of length 1? – Ben I. Oct 23 '17 at 17:01
  • 1
    Just an aside, no `String` will ever be equal to `'a'`, or any other `char`. Did you mean `someString.equals("a")`? – azurefrog Oct 23 '17 at 17:03

3 Answers3

2

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))
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
2

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.

Derek Brown
  • 4,232
  • 4
  • 27
  • 44
0

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

Ben I.
  • 1,065
  • 1
  • 13
  • 29