Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.equals() with multiple conditions (and one action on result) [duplicate]

Tags:

java

android

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.

like image 379
sandalone Avatar asked Apr 18 '12 11:04

sandalone


People also ask

How do you check if a string has multiple values?

To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable.

Are strings equal in Java?

Java String equals() MethodThe 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 you write not equal to in Java?

The symbols used for Not Equal operator is != . Not Equal operator takes two operands: left operand and right operand as shown in the following. The operator returns a boolean value of true if x is not equal to y , or false if not.


1 Answers

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)) { } 
like image 157
hmjd Avatar answered Sep 22 '22 08:09

hmjd