zPushz
zPushz

Reputation: 67

How to write multiple equalsIgnoreCase() in one statement?

Is there a way to implement something like this without giving operand errors?

if (check.equalsIgnoreCase("a"|| "e" || "i" || "o" || "u")) {}

Upvotes: 2

Views: 979

Answers (4)

M. Justin
M. Justin

Reputation: 21239

if (Stream.of("a", "e", "i", "o", "u").anyMatch(check::equalsIgnoreCase)) {
  // ...
}

This will return true if any of the elements in the given Stream return true for check.equalsIgnoreCase(element), where element is the stream element.

This calls the anyMatch(Predicate) method against the stream consisting of the five strings. Since equalsIgnoreCase takes a string and returns a boolean, check::equalsIgnoreCase can be used as a method reference lambda expression as a Predicate<String>.

Upvotes: 3

Harshal Parekh
Harshal Parekh

Reputation: 6017

There are 2 answers already. Using logical operators and regex.

Here is another approach using .indexOf(...).

if (“aeiou”.indexOf(check) >= 0) {
    // your code here
 }

Upvotes: 3

jubnzv
jubnzv

Reputation: 1584

You can also consider String.matches which takes a regular expression and tells that the string match it or not:

if (check.matches("a|e|i|o|u"))

Or, for case insensitivity:

if (check.matches("(?i)a|e|i|o|u"))

This is certainly overkill if you just need to match a single letter in a string, and the correct answer for your question was given by @geanakuch, so please accept it. But this solution can be useful in the other cases, when you need to deal with more complex patterns in strings comparison.

Upvotes: 1

geanakuch
geanakuch

Reputation: 972

Logical operators only work on booleans, you're trying to use them on Strings. Do this instead:

if(check.equalsIgnoreCase("a")
        || check.equalIgnoreCase("e")
        || check.equalIgnoreCase("i")
        || check.equalIgnoreCase("o")
        || check.equalIgnoreCase("u")) {
    // Your code here
}

Also you can flip the expression to avoid null-checks: "a".equalsIgnoreCase(check).

You could also look into regular expressions which would make the code a lot more compact. But as you say you're just starting, I think this will do for now.

Upvotes: 1

Related Questions