Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare one String with multiple values in one expression

Tags:

java

string

regex

I have one String variable, str with possible values, val1, val2 and val3.

I want to compare (with equal case) str to all of these values using an if statement, for example:

if("val1".equalsIgnoreCase(str)||"val2".equalsIgnoreCase(str)||"val3".equalsIgnoreCase(str)) {       //remaining code } 

Is there a way to avoid using multiple OR (||) operators and compare values in one expression? For example, like this:

 if(("val1" OR "val2" OR "val3").equalsIgnoreCase(str)   //this is only an idea. 
like image 356
kundan bora Avatar asked Apr 18 '12 08:04

kundan bora


People also ask

Can we use == for string comparison?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


1 Answers

I found the better solution. This can be achieved through RegEx:

if (str.matches("val1|val2|val3")) {      // remaining code } 

For case insensitive matching:

if (str.matches("(?i)val1|val2|val3")) {      // remaining code } 
like image 83
kundan bora Avatar answered Oct 19 '22 15:10

kundan bora