Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if String x equals any of the Strings from String[]

Tags:

java

I am trying to set a boolean true if a user-entered string equals any of the strings from a string array.

I have improvised and came up with this

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean valueEqualsCancel = true;
for(String cancelWord : cancelWords) {
  if(!valueEqualsCancel) break;
  valueEqualsCancel =  valueEqualsCancel && value.equals(cancelWord);
}

But valueEqualsCancel is never true.

Any tips?

like image 711
Matt Smith Avatar asked Aug 04 '13 15:08

Matt Smith


People also ask

How do you check if a string equals a string?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

How do I check if a string contains any value?

The third method you can use to check if one String contains another in Java is contains() method of String. This method returns true if a substring is present in String, or false otherwise. The only difference between contains() and indexOf() is that the former returns a boolean value while later returns an int value.

What is a string [] in Java?

In Java, a string is an object that represents a number of character values. Each letter in the string is a separate character value that makes up the Java string object. Characters in Java are represented by the char class. Users can write an array of char values that will mean the same thing as a string.


3 Answers

You can do something like:

Arrays.asList(cancelWords).contains(value)

(see Arrays.asList())

If you're going to be doing multiple queries like this, then put all of your words in a Set and query that.

like image 177
arshajii Avatar answered Oct 14 '22 17:10

arshajii


Convert the Array to a List and then use the contains method to check.

Arrays.asList(cancelWords).contains(value)

like image 33
JHS Avatar answered Oct 14 '22 17:10

JHS


Here is a 2-liner using Java 8 that is easy to read:

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean valueEqualsCancel = Arrays.stream(cancelWords).anyMatch(value::equals);
like image 5
Matt Avatar answered Oct 14 '22 17:10

Matt