69

Is it possible to do something like this in Java for Android (this is a pseudo code)

IF (some_string.equals("john" OR "mary" OR "peter" OR "etc."){
   THEN do something
}

?

At the moment this is done via multiple String.equals() condition with || among them.

sandalone
  • 41,141
  • 63
  • 222
  • 338

7 Answers7

180

Possibilities:

  • Use String.equals():

    if (some_string.equals("john") ||
        some_string.equals("mary") ||
        some_string.equals("peter"))
    {
    }
    
  • Use a regular expression:

    if (some_string.matches("john|mary|peter"))
    {
    }
    
  • Store a list of strings to be matched against in a Collection and search the collection:

    Set<String> names = new HashSet<String>();
    names.add("john");
    names.add("mary");
    names.add("peter");
    
    if (names.contains(some_string))
    {
    }
    
hmjd
  • 120,187
  • 20
  • 207
  • 252
67
if (Arrays.asList("John", "Mary", "Peter").contains(name)) {
}
  • This is not as fast as using a prepared Set, but it performs no worse than using OR.
  • This doesn't crash when name is NULL (same with Set).
  • I like it because it looks clean
Sarsaparilla
  • 6,300
  • 1
  • 32
  • 21
  • somewhat late to the party, but for the null check, you should do "Peter".equals(name). That way you don't have a possible null object to invoke an operation on – ShadowFlame Jun 14 '22 at 12:30
8

Keep the acceptable values in a HashSet and check if your string exists using the contains method:

Set<String> accept = new HashSet<String>(Arrays.asList(new String[] {"john", "mary", "peter"}));
if (accept.contains(some_string)) {
    //...
}
krock
  • 28,904
  • 13
  • 79
  • 85
3

Your current implementation is correct. The suggested is not possible but the pseudo code would be implemented with multiple equal() calls and ||.

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
1

If you develop for Android KitKat or newer, you could also use a switch statement (see: Android coding with switch (String)). e.g.

switch(yourString)
{
     case "john":
          //do something for john
     case "mary":
          //do something for mary
}
Rafael Palomino
  • 318
  • 2
  • 14
Boardy
  • 35,417
  • 104
  • 256
  • 447
-1

No,its check like if string is "john" OR "mary" OR "peter" OR "etc."

you should check using ||

Like.,,if(str.equals("john") || str.equals("mary") || str.equals("peter"))

Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
-1
Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with

while (m.find()) {
    //do something???
}   

Use regex to find a match maybe?

Or create an array

 String[] a = new String[]{
        "tom",
        "bob",
        "harry"
 };

 if(a.contains(stringtomatch)){
     //do something
 }
FabianCook
  • 20,269
  • 16
  • 67
  • 115