Compare one String with multiple values in one expression












51















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.









share|improve this question




















  • 1





    possible duplicate of A Cleaner IF Statement

    – WoodenKitty
    Jan 17 '15 at 3:07
















51















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.









share|improve this question




















  • 1





    possible duplicate of A Cleaner IF Statement

    – WoodenKitty
    Jan 17 '15 at 3:07














51












51








51


9






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.









share|improve this question
















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.






java regex string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 2 '15 at 4:45







kundan bora

















asked Apr 18 '12 at 8:13









kundan borakundan bora

2,72811527




2,72811527








  • 1





    possible duplicate of A Cleaner IF Statement

    – WoodenKitty
    Jan 17 '15 at 3:07














  • 1





    possible duplicate of A Cleaner IF Statement

    – WoodenKitty
    Jan 17 '15 at 3:07








1




1





possible duplicate of A Cleaner IF Statement

– WoodenKitty
Jan 17 '15 at 3:07





possible duplicate of A Cleaner IF Statement

– WoodenKitty
Jan 17 '15 at 3:07












12 Answers
12






active

oldest

votes


















83














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
}





share|improve this answer


























  • The matches function does not work well for all cases. The answer of @hmjd did it for my case. See Regex doesn't work in String.matches() for more info.

    – Primoz990
    May 11 '17 at 10:20





















31














In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like



if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
// ...
}





share|improve this answer





















  • 4





    This should be the accepted answer!

    – higuaro
    Aug 11 '17 at 6:33



















12














You could store all the strings that you want to compare str with into a collection and check if the collection contains str. Store all strings in the collection as lowercase and convert str to lowercase before querying the collection. For example:



Set<String> strings = new HashSet<String>();
strings.add("val1");
strings.add("val2");

String str = "Val1";

if (strings.contains(str.toLowerCase()))
{
}





share|improve this answer
























  • What if str contain value like "val" only ???

    – kundan bora
    Apr 18 '12 at 8:23











  • You can populate the collection with whatever values you require. In case if str was "val" then in the code in my answer strings.contains() would return false.

    – hmjd
    Apr 18 '12 at 8:25











  • No no i am saying that if someone pass str value as "Val" which is not as equal as "Val1","Val2,"Val3". That mean passing str value as "Val" must be failed.. but in your case this will be pass.Not satisfy my condition.

    – kundan bora
    Apr 18 '12 at 8:28











  • From the question case is irrelevant due to presence of equalsIgnoreCase(). If "Val" is passed and strings contains "val1", "val2", and "val3" then contains() will return false. See ideone.com/LiYKP .

    – hmjd
    Apr 18 '12 at 8:35













  • Oh you used HashSet to store Strings . OK I got this.

    – kundan bora
    Apr 18 '12 at 9:24



















4














ArrayUtils may be helpful.



ArrayUtils.contains(new String{"1", "2"}, "1")





share|improve this answer































    3














    Small enhancement to perfectly valid @hmjd's answer: you can use following syntax:





    class A {

    final Set<String> strings = new HashSet<>() {{
    add("val1");
    add("val2");
    }};

    // ...

    if (strings.contains(str.toLowerCase())) {
    }

    // ...
    }


    It allows you to initialize you Set in-place.






    share|improve this answer

































      2














      Just use var-args and write your own static method:



      public static boolean compareWithMany(String first, String next, String ... rest)
      {
      if(first.equalsIgnoreCase(next))
      return true;
      for(int i = 0; i < rest.length; i++)
      {
      if(first.equalsIgnoreCase(rest[i]))
      return true;
      }
      return false;
      }

      public static void main(String args)
      {
      final String str = "val1";
      System.out.println(compareWithMany(str, "val1", "val2", "val3"));
      }





      share|improve this answer
























      • I like this one! I'm probably overlooking something, but why do you include next as a parameter? That can just as well be part of the var-args rest, right?

        – Martijn
        May 10 '15 at 9:44













      • By having 'next' I enforce passing at least one parameter. So you can not do compareWithMany("foo"). It's a compile-time sanity check, instead of having to deal with an empty set to compare against during runtime.

        – Neet
        May 11 '15 at 18:00





















      1














      Yet another alternative (kinda similar to https://stackoverflow.com/a/32241628/6095216 above) using StringUtils from the apache commons library: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#equalsAnyIgnoreCase-java.lang.CharSequence-java.lang.CharSequence...-



      if (StringUtils.equalsAnyIgnoreCase(str, "val1", "val2", "val3")) {
      // remaining code
      }





      share|improve this answer































        0














        You can achieve this with Collections framework. Put all your options in a Collection say something like Collection<String> options ;



        Then loop throgh this to compare your string with the list elements and if it is you can return a boolean value true and otherwise false.






        share|improve this answer































          0














          Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:



          if ("A C Viking G M Ocelot".contains(mAnswer)) {...}


          for numbers it's a tad more involved but still works:



          if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...} 





          share|improve this answer

































            0














            Apache Commons Collection class.



            StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)



            So in your case, it would be



            StringUtils.equalsAny(str, "val1", "val2", "val3");






            share|improve this answer































              -2














              No, there is no such possibility.
              Allthough, one could imagine:



              public static boolean contains(String s, Collection<String>c) {
              for (String ss : c) {
              if (s.equalsIgnoreCase(ss)) return true;
              }
              return false;
              }





              share|improve this answer
























              • For the collections worth to consider, like HashSet, contains() has much more efficient implementation.

                – Alexei Kaigorodov
                Apr 18 '12 at 8:24











              • True, but (which may be a moot point), equals and equalsIgnoreCase do not yield the same result. This could of course be overcome by storing the strings as lower case and lowercasing the key you're looking for, but, YMMV

                – slipset
                Apr 18 '12 at 8:27



















              -3














              !string.matches("a|b|c|d") 


              works fine for me.






              share|improve this answer





















              • 6





                Please give explanation / reason for better answer, It is too short

                – sangram parmar
                Nov 10 '16 at 10:14








              • 1





                How is this different from the accepted answer?

                – Jiri Tousek
                Nov 14 '16 at 12:24











              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10205437%2fcompare-one-string-with-multiple-values-in-one-expression%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              12 Answers
              12






              active

              oldest

              votes








              12 Answers
              12






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              83














              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
              }





              share|improve this answer


























              • The matches function does not work well for all cases. The answer of @hmjd did it for my case. See Regex doesn't work in String.matches() for more info.

                – Primoz990
                May 11 '17 at 10:20


















              83














              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
              }





              share|improve this answer


























              • The matches function does not work well for all cases. The answer of @hmjd did it for my case. See Regex doesn't work in String.matches() for more info.

                – Primoz990
                May 11 '17 at 10:20
















              83












              83








              83







              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
              }





              share|improve this answer















              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
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 3 '18 at 7:07

























              answered Apr 18 '12 at 15:59









              kundan borakundan bora

              2,72811527




              2,72811527













              • The matches function does not work well for all cases. The answer of @hmjd did it for my case. See Regex doesn't work in String.matches() for more info.

                – Primoz990
                May 11 '17 at 10:20





















              • The matches function does not work well for all cases. The answer of @hmjd did it for my case. See Regex doesn't work in String.matches() for more info.

                – Primoz990
                May 11 '17 at 10:20



















              The matches function does not work well for all cases. The answer of @hmjd did it for my case. See Regex doesn't work in String.matches() for more info.

              – Primoz990
              May 11 '17 at 10:20







              The matches function does not work well for all cases. The answer of @hmjd did it for my case. See Regex doesn't work in String.matches() for more info.

              – Primoz990
              May 11 '17 at 10:20















              31














              In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like



              if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
              // ...
              }





              share|improve this answer





















              • 4





                This should be the accepted answer!

                – higuaro
                Aug 11 '17 at 6:33
















              31














              In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like



              if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
              // ...
              }





              share|improve this answer





















              • 4





                This should be the accepted answer!

                – higuaro
                Aug 11 '17 at 6:33














              31












              31








              31







              In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like



              if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
              // ...
              }





              share|improve this answer















              In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like



              if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
              // ...
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 6 '17 at 17:17









              ZhekaKozlov

              14.8k866111




              14.8k866111










              answered Dec 3 '16 at 21:08









              Elliott FrischElliott Frisch

              153k1389178




              153k1389178








              • 4





                This should be the accepted answer!

                – higuaro
                Aug 11 '17 at 6:33














              • 4





                This should be the accepted answer!

                – higuaro
                Aug 11 '17 at 6:33








              4




              4





              This should be the accepted answer!

              – higuaro
              Aug 11 '17 at 6:33





              This should be the accepted answer!

              – higuaro
              Aug 11 '17 at 6:33











              12














              You could store all the strings that you want to compare str with into a collection and check if the collection contains str. Store all strings in the collection as lowercase and convert str to lowercase before querying the collection. For example:



              Set<String> strings = new HashSet<String>();
              strings.add("val1");
              strings.add("val2");

              String str = "Val1";

              if (strings.contains(str.toLowerCase()))
              {
              }





              share|improve this answer
























              • What if str contain value like "val" only ???

                – kundan bora
                Apr 18 '12 at 8:23











              • You can populate the collection with whatever values you require. In case if str was "val" then in the code in my answer strings.contains() would return false.

                – hmjd
                Apr 18 '12 at 8:25











              • No no i am saying that if someone pass str value as "Val" which is not as equal as "Val1","Val2,"Val3". That mean passing str value as "Val" must be failed.. but in your case this will be pass.Not satisfy my condition.

                – kundan bora
                Apr 18 '12 at 8:28











              • From the question case is irrelevant due to presence of equalsIgnoreCase(). If "Val" is passed and strings contains "val1", "val2", and "val3" then contains() will return false. See ideone.com/LiYKP .

                – hmjd
                Apr 18 '12 at 8:35













              • Oh you used HashSet to store Strings . OK I got this.

                – kundan bora
                Apr 18 '12 at 9:24
















              12














              You could store all the strings that you want to compare str with into a collection and check if the collection contains str. Store all strings in the collection as lowercase and convert str to lowercase before querying the collection. For example:



              Set<String> strings = new HashSet<String>();
              strings.add("val1");
              strings.add("val2");

              String str = "Val1";

              if (strings.contains(str.toLowerCase()))
              {
              }





              share|improve this answer
























              • What if str contain value like "val" only ???

                – kundan bora
                Apr 18 '12 at 8:23











              • You can populate the collection with whatever values you require. In case if str was "val" then in the code in my answer strings.contains() would return false.

                – hmjd
                Apr 18 '12 at 8:25











              • No no i am saying that if someone pass str value as "Val" which is not as equal as "Val1","Val2,"Val3". That mean passing str value as "Val" must be failed.. but in your case this will be pass.Not satisfy my condition.

                – kundan bora
                Apr 18 '12 at 8:28











              • From the question case is irrelevant due to presence of equalsIgnoreCase(). If "Val" is passed and strings contains "val1", "val2", and "val3" then contains() will return false. See ideone.com/LiYKP .

                – hmjd
                Apr 18 '12 at 8:35













              • Oh you used HashSet to store Strings . OK I got this.

                – kundan bora
                Apr 18 '12 at 9:24














              12












              12








              12







              You could store all the strings that you want to compare str with into a collection and check if the collection contains str. Store all strings in the collection as lowercase and convert str to lowercase before querying the collection. For example:



              Set<String> strings = new HashSet<String>();
              strings.add("val1");
              strings.add("val2");

              String str = "Val1";

              if (strings.contains(str.toLowerCase()))
              {
              }





              share|improve this answer













              You could store all the strings that you want to compare str with into a collection and check if the collection contains str. Store all strings in the collection as lowercase and convert str to lowercase before querying the collection. For example:



              Set<String> strings = new HashSet<String>();
              strings.add("val1");
              strings.add("val2");

              String str = "Val1";

              if (strings.contains(str.toLowerCase()))
              {
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 18 '12 at 8:16









              hmjdhmjd

              102k13161217




              102k13161217













              • What if str contain value like "val" only ???

                – kundan bora
                Apr 18 '12 at 8:23











              • You can populate the collection with whatever values you require. In case if str was "val" then in the code in my answer strings.contains() would return false.

                – hmjd
                Apr 18 '12 at 8:25











              • No no i am saying that if someone pass str value as "Val" which is not as equal as "Val1","Val2,"Val3". That mean passing str value as "Val" must be failed.. but in your case this will be pass.Not satisfy my condition.

                – kundan bora
                Apr 18 '12 at 8:28











              • From the question case is irrelevant due to presence of equalsIgnoreCase(). If "Val" is passed and strings contains "val1", "val2", and "val3" then contains() will return false. See ideone.com/LiYKP .

                – hmjd
                Apr 18 '12 at 8:35













              • Oh you used HashSet to store Strings . OK I got this.

                – kundan bora
                Apr 18 '12 at 9:24



















              • What if str contain value like "val" only ???

                – kundan bora
                Apr 18 '12 at 8:23











              • You can populate the collection with whatever values you require. In case if str was "val" then in the code in my answer strings.contains() would return false.

                – hmjd
                Apr 18 '12 at 8:25











              • No no i am saying that if someone pass str value as "Val" which is not as equal as "Val1","Val2,"Val3". That mean passing str value as "Val" must be failed.. but in your case this will be pass.Not satisfy my condition.

                – kundan bora
                Apr 18 '12 at 8:28











              • From the question case is irrelevant due to presence of equalsIgnoreCase(). If "Val" is passed and strings contains "val1", "val2", and "val3" then contains() will return false. See ideone.com/LiYKP .

                – hmjd
                Apr 18 '12 at 8:35













              • Oh you used HashSet to store Strings . OK I got this.

                – kundan bora
                Apr 18 '12 at 9:24

















              What if str contain value like "val" only ???

              – kundan bora
              Apr 18 '12 at 8:23





              What if str contain value like "val" only ???

              – kundan bora
              Apr 18 '12 at 8:23













              You can populate the collection with whatever values you require. In case if str was "val" then in the code in my answer strings.contains() would return false.

              – hmjd
              Apr 18 '12 at 8:25





              You can populate the collection with whatever values you require. In case if str was "val" then in the code in my answer strings.contains() would return false.

              – hmjd
              Apr 18 '12 at 8:25













              No no i am saying that if someone pass str value as "Val" which is not as equal as "Val1","Val2,"Val3". That mean passing str value as "Val" must be failed.. but in your case this will be pass.Not satisfy my condition.

              – kundan bora
              Apr 18 '12 at 8:28





              No no i am saying that if someone pass str value as "Val" which is not as equal as "Val1","Val2,"Val3". That mean passing str value as "Val" must be failed.. but in your case this will be pass.Not satisfy my condition.

              – kundan bora
              Apr 18 '12 at 8:28













              From the question case is irrelevant due to presence of equalsIgnoreCase(). If "Val" is passed and strings contains "val1", "val2", and "val3" then contains() will return false. See ideone.com/LiYKP .

              – hmjd
              Apr 18 '12 at 8:35







              From the question case is irrelevant due to presence of equalsIgnoreCase(). If "Val" is passed and strings contains "val1", "val2", and "val3" then contains() will return false. See ideone.com/LiYKP .

              – hmjd
              Apr 18 '12 at 8:35















              Oh you used HashSet to store Strings . OK I got this.

              – kundan bora
              Apr 18 '12 at 9:24





              Oh you used HashSet to store Strings . OK I got this.

              – kundan bora
              Apr 18 '12 at 9:24











              4














              ArrayUtils may be helpful.



              ArrayUtils.contains(new String{"1", "2"}, "1")





              share|improve this answer




























                4














                ArrayUtils may be helpful.



                ArrayUtils.contains(new String{"1", "2"}, "1")





                share|improve this answer


























                  4












                  4








                  4







                  ArrayUtils may be helpful.



                  ArrayUtils.contains(new String{"1", "2"}, "1")





                  share|improve this answer













                  ArrayUtils may be helpful.



                  ArrayUtils.contains(new String{"1", "2"}, "1")






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Aug 27 '15 at 5:53









                  Jeffrey4lJeffrey4l

                  685




                  685























                      3














                      Small enhancement to perfectly valid @hmjd's answer: you can use following syntax:





                      class A {

                      final Set<String> strings = new HashSet<>() {{
                      add("val1");
                      add("val2");
                      }};

                      // ...

                      if (strings.contains(str.toLowerCase())) {
                      }

                      // ...
                      }


                      It allows you to initialize you Set in-place.






                      share|improve this answer






























                        3














                        Small enhancement to perfectly valid @hmjd's answer: you can use following syntax:





                        class A {

                        final Set<String> strings = new HashSet<>() {{
                        add("val1");
                        add("val2");
                        }};

                        // ...

                        if (strings.contains(str.toLowerCase())) {
                        }

                        // ...
                        }


                        It allows you to initialize you Set in-place.






                        share|improve this answer




























                          3












                          3








                          3







                          Small enhancement to perfectly valid @hmjd's answer: you can use following syntax:





                          class A {

                          final Set<String> strings = new HashSet<>() {{
                          add("val1");
                          add("val2");
                          }};

                          // ...

                          if (strings.contains(str.toLowerCase())) {
                          }

                          // ...
                          }


                          It allows you to initialize you Set in-place.






                          share|improve this answer















                          Small enhancement to perfectly valid @hmjd's answer: you can use following syntax:





                          class A {

                          final Set<String> strings = new HashSet<>() {{
                          add("val1");
                          add("val2");
                          }};

                          // ...

                          if (strings.contains(str.toLowerCase())) {
                          }

                          // ...
                          }


                          It allows you to initialize you Set in-place.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited May 23 '17 at 12:10









                          Community

                          11




                          11










                          answered Sep 14 '15 at 10:51









                          Andrey StarodubtsevAndrey Starodubtsev

                          3,87522037




                          3,87522037























                              2














                              Just use var-args and write your own static method:



                              public static boolean compareWithMany(String first, String next, String ... rest)
                              {
                              if(first.equalsIgnoreCase(next))
                              return true;
                              for(int i = 0; i < rest.length; i++)
                              {
                              if(first.equalsIgnoreCase(rest[i]))
                              return true;
                              }
                              return false;
                              }

                              public static void main(String args)
                              {
                              final String str = "val1";
                              System.out.println(compareWithMany(str, "val1", "val2", "val3"));
                              }





                              share|improve this answer
























                              • I like this one! I'm probably overlooking something, but why do you include next as a parameter? That can just as well be part of the var-args rest, right?

                                – Martijn
                                May 10 '15 at 9:44













                              • By having 'next' I enforce passing at least one parameter. So you can not do compareWithMany("foo"). It's a compile-time sanity check, instead of having to deal with an empty set to compare against during runtime.

                                – Neet
                                May 11 '15 at 18:00


















                              2














                              Just use var-args and write your own static method:



                              public static boolean compareWithMany(String first, String next, String ... rest)
                              {
                              if(first.equalsIgnoreCase(next))
                              return true;
                              for(int i = 0; i < rest.length; i++)
                              {
                              if(first.equalsIgnoreCase(rest[i]))
                              return true;
                              }
                              return false;
                              }

                              public static void main(String args)
                              {
                              final String str = "val1";
                              System.out.println(compareWithMany(str, "val1", "val2", "val3"));
                              }





                              share|improve this answer
























                              • I like this one! I'm probably overlooking something, but why do you include next as a parameter? That can just as well be part of the var-args rest, right?

                                – Martijn
                                May 10 '15 at 9:44













                              • By having 'next' I enforce passing at least one parameter. So you can not do compareWithMany("foo"). It's a compile-time sanity check, instead of having to deal with an empty set to compare against during runtime.

                                – Neet
                                May 11 '15 at 18:00
















                              2












                              2








                              2







                              Just use var-args and write your own static method:



                              public static boolean compareWithMany(String first, String next, String ... rest)
                              {
                              if(first.equalsIgnoreCase(next))
                              return true;
                              for(int i = 0; i < rest.length; i++)
                              {
                              if(first.equalsIgnoreCase(rest[i]))
                              return true;
                              }
                              return false;
                              }

                              public static void main(String args)
                              {
                              final String str = "val1";
                              System.out.println(compareWithMany(str, "val1", "val2", "val3"));
                              }





                              share|improve this answer













                              Just use var-args and write your own static method:



                              public static boolean compareWithMany(String first, String next, String ... rest)
                              {
                              if(first.equalsIgnoreCase(next))
                              return true;
                              for(int i = 0; i < rest.length; i++)
                              {
                              if(first.equalsIgnoreCase(rest[i]))
                              return true;
                              }
                              return false;
                              }

                              public static void main(String args)
                              {
                              final String str = "val1";
                              System.out.println(compareWithMany(str, "val1", "val2", "val3"));
                              }






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Apr 18 '12 at 8:19









                              NeetNeet

                              3,3771016




                              3,3771016













                              • I like this one! I'm probably overlooking something, but why do you include next as a parameter? That can just as well be part of the var-args rest, right?

                                – Martijn
                                May 10 '15 at 9:44













                              • By having 'next' I enforce passing at least one parameter. So you can not do compareWithMany("foo"). It's a compile-time sanity check, instead of having to deal with an empty set to compare against during runtime.

                                – Neet
                                May 11 '15 at 18:00





















                              • I like this one! I'm probably overlooking something, but why do you include next as a parameter? That can just as well be part of the var-args rest, right?

                                – Martijn
                                May 10 '15 at 9:44













                              • By having 'next' I enforce passing at least one parameter. So you can not do compareWithMany("foo"). It's a compile-time sanity check, instead of having to deal with an empty set to compare against during runtime.

                                – Neet
                                May 11 '15 at 18:00



















                              I like this one! I'm probably overlooking something, but why do you include next as a parameter? That can just as well be part of the var-args rest, right?

                              – Martijn
                              May 10 '15 at 9:44







                              I like this one! I'm probably overlooking something, but why do you include next as a parameter? That can just as well be part of the var-args rest, right?

                              – Martijn
                              May 10 '15 at 9:44















                              By having 'next' I enforce passing at least one parameter. So you can not do compareWithMany("foo"). It's a compile-time sanity check, instead of having to deal with an empty set to compare against during runtime.

                              – Neet
                              May 11 '15 at 18:00







                              By having 'next' I enforce passing at least one parameter. So you can not do compareWithMany("foo"). It's a compile-time sanity check, instead of having to deal with an empty set to compare against during runtime.

                              – Neet
                              May 11 '15 at 18:00













                              1














                              Yet another alternative (kinda similar to https://stackoverflow.com/a/32241628/6095216 above) using StringUtils from the apache commons library: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#equalsAnyIgnoreCase-java.lang.CharSequence-java.lang.CharSequence...-



                              if (StringUtils.equalsAnyIgnoreCase(str, "val1", "val2", "val3")) {
                              // remaining code
                              }





                              share|improve this answer




























                                1














                                Yet another alternative (kinda similar to https://stackoverflow.com/a/32241628/6095216 above) using StringUtils from the apache commons library: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#equalsAnyIgnoreCase-java.lang.CharSequence-java.lang.CharSequence...-



                                if (StringUtils.equalsAnyIgnoreCase(str, "val1", "val2", "val3")) {
                                // remaining code
                                }





                                share|improve this answer


























                                  1












                                  1








                                  1







                                  Yet another alternative (kinda similar to https://stackoverflow.com/a/32241628/6095216 above) using StringUtils from the apache commons library: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#equalsAnyIgnoreCase-java.lang.CharSequence-java.lang.CharSequence...-



                                  if (StringUtils.equalsAnyIgnoreCase(str, "val1", "val2", "val3")) {
                                  // remaining code
                                  }





                                  share|improve this answer













                                  Yet another alternative (kinda similar to https://stackoverflow.com/a/32241628/6095216 above) using StringUtils from the apache commons library: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#equalsAnyIgnoreCase-java.lang.CharSequence-java.lang.CharSequence...-



                                  if (StringUtils.equalsAnyIgnoreCase(str, "val1", "val2", "val3")) {
                                  // remaining code
                                  }






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 19 '18 at 23:06









                                  YuryYury

                                  13218




                                  13218























                                      0














                                      You can achieve this with Collections framework. Put all your options in a Collection say something like Collection<String> options ;



                                      Then loop throgh this to compare your string with the list elements and if it is you can return a boolean value true and otherwise false.






                                      share|improve this answer




























                                        0














                                        You can achieve this with Collections framework. Put all your options in a Collection say something like Collection<String> options ;



                                        Then loop throgh this to compare your string with the list elements and if it is you can return a boolean value true and otherwise false.






                                        share|improve this answer


























                                          0












                                          0








                                          0







                                          You can achieve this with Collections framework. Put all your options in a Collection say something like Collection<String> options ;



                                          Then loop throgh this to compare your string with the list elements and if it is you can return a boolean value true and otherwise false.






                                          share|improve this answer













                                          You can achieve this with Collections framework. Put all your options in a Collection say something like Collection<String> options ;



                                          Then loop throgh this to compare your string with the list elements and if it is you can return a boolean value true and otherwise false.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Apr 18 '12 at 8:21









                                          Tijo K VargheseTijo K Varghese

                                          1,33293253




                                          1,33293253























                                              0














                                              Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:



                                              if ("A C Viking G M Ocelot".contains(mAnswer)) {...}


                                              for numbers it's a tad more involved but still works:



                                              if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...} 





                                              share|improve this answer






























                                                0














                                                Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:



                                                if ("A C Viking G M Ocelot".contains(mAnswer)) {...}


                                                for numbers it's a tad more involved but still works:



                                                if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...} 





                                                share|improve this answer




























                                                  0












                                                  0








                                                  0







                                                  Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:



                                                  if ("A C Viking G M Ocelot".contains(mAnswer)) {...}


                                                  for numbers it's a tad more involved but still works:



                                                  if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...} 





                                                  share|improve this answer















                                                  Remember in Java a quoted String is still a String object. Therefore you can use the String function contains() to test for a range of Strings or integers using this method:



                                                  if ("A C Viking G M Ocelot".contains(mAnswer)) {...}


                                                  for numbers it's a tad more involved but still works:



                                                  if ("1 4 5 9 10 17 23 96457".contains(String.valueOf(mNumAnswer))) {...} 






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Jan 19 '17 at 8:52

























                                                  answered Jan 19 '17 at 8:46









                                                  Stuart WalshStuart Walsh

                                                  2112




                                                  2112























                                                      0














                                                      Apache Commons Collection class.



                                                      StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)



                                                      So in your case, it would be



                                                      StringUtils.equalsAny(str, "val1", "val2", "val3");






                                                      share|improve this answer




























                                                        0














                                                        Apache Commons Collection class.



                                                        StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)



                                                        So in your case, it would be



                                                        StringUtils.equalsAny(str, "val1", "val2", "val3");






                                                        share|improve this answer


























                                                          0












                                                          0








                                                          0







                                                          Apache Commons Collection class.



                                                          StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)



                                                          So in your case, it would be



                                                          StringUtils.equalsAny(str, "val1", "val2", "val3");






                                                          share|improve this answer













                                                          Apache Commons Collection class.



                                                          StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)



                                                          So in your case, it would be



                                                          StringUtils.equalsAny(str, "val1", "val2", "val3");







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Dec 26 '18 at 18:40









                                                          user3583333user3583333

                                                          112




                                                          112























                                                              -2














                                                              No, there is no such possibility.
                                                              Allthough, one could imagine:



                                                              public static boolean contains(String s, Collection<String>c) {
                                                              for (String ss : c) {
                                                              if (s.equalsIgnoreCase(ss)) return true;
                                                              }
                                                              return false;
                                                              }





                                                              share|improve this answer
























                                                              • For the collections worth to consider, like HashSet, contains() has much more efficient implementation.

                                                                – Alexei Kaigorodov
                                                                Apr 18 '12 at 8:24











                                                              • True, but (which may be a moot point), equals and equalsIgnoreCase do not yield the same result. This could of course be overcome by storing the strings as lower case and lowercasing the key you're looking for, but, YMMV

                                                                – slipset
                                                                Apr 18 '12 at 8:27
















                                                              -2














                                                              No, there is no such possibility.
                                                              Allthough, one could imagine:



                                                              public static boolean contains(String s, Collection<String>c) {
                                                              for (String ss : c) {
                                                              if (s.equalsIgnoreCase(ss)) return true;
                                                              }
                                                              return false;
                                                              }





                                                              share|improve this answer
























                                                              • For the collections worth to consider, like HashSet, contains() has much more efficient implementation.

                                                                – Alexei Kaigorodov
                                                                Apr 18 '12 at 8:24











                                                              • True, but (which may be a moot point), equals and equalsIgnoreCase do not yield the same result. This could of course be overcome by storing the strings as lower case and lowercasing the key you're looking for, but, YMMV

                                                                – slipset
                                                                Apr 18 '12 at 8:27














                                                              -2












                                                              -2








                                                              -2







                                                              No, there is no such possibility.
                                                              Allthough, one could imagine:



                                                              public static boolean contains(String s, Collection<String>c) {
                                                              for (String ss : c) {
                                                              if (s.equalsIgnoreCase(ss)) return true;
                                                              }
                                                              return false;
                                                              }





                                                              share|improve this answer













                                                              No, there is no such possibility.
                                                              Allthough, one could imagine:



                                                              public static boolean contains(String s, Collection<String>c) {
                                                              for (String ss : c) {
                                                              if (s.equalsIgnoreCase(ss)) return true;
                                                              }
                                                              return false;
                                                              }






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Apr 18 '12 at 8:17









                                                              slipsetslipset

                                                              2,26721616




                                                              2,26721616













                                                              • For the collections worth to consider, like HashSet, contains() has much more efficient implementation.

                                                                – Alexei Kaigorodov
                                                                Apr 18 '12 at 8:24











                                                              • True, but (which may be a moot point), equals and equalsIgnoreCase do not yield the same result. This could of course be overcome by storing the strings as lower case and lowercasing the key you're looking for, but, YMMV

                                                                – slipset
                                                                Apr 18 '12 at 8:27



















                                                              • For the collections worth to consider, like HashSet, contains() has much more efficient implementation.

                                                                – Alexei Kaigorodov
                                                                Apr 18 '12 at 8:24











                                                              • True, but (which may be a moot point), equals and equalsIgnoreCase do not yield the same result. This could of course be overcome by storing the strings as lower case and lowercasing the key you're looking for, but, YMMV

                                                                – slipset
                                                                Apr 18 '12 at 8:27

















                                                              For the collections worth to consider, like HashSet, contains() has much more efficient implementation.

                                                              – Alexei Kaigorodov
                                                              Apr 18 '12 at 8:24





                                                              For the collections worth to consider, like HashSet, contains() has much more efficient implementation.

                                                              – Alexei Kaigorodov
                                                              Apr 18 '12 at 8:24













                                                              True, but (which may be a moot point), equals and equalsIgnoreCase do not yield the same result. This could of course be overcome by storing the strings as lower case and lowercasing the key you're looking for, but, YMMV

                                                              – slipset
                                                              Apr 18 '12 at 8:27





                                                              True, but (which may be a moot point), equals and equalsIgnoreCase do not yield the same result. This could of course be overcome by storing the strings as lower case and lowercasing the key you're looking for, but, YMMV

                                                              – slipset
                                                              Apr 18 '12 at 8:27











                                                              -3














                                                              !string.matches("a|b|c|d") 


                                                              works fine for me.






                                                              share|improve this answer





















                                                              • 6





                                                                Please give explanation / reason for better answer, It is too short

                                                                – sangram parmar
                                                                Nov 10 '16 at 10:14








                                                              • 1





                                                                How is this different from the accepted answer?

                                                                – Jiri Tousek
                                                                Nov 14 '16 at 12:24
















                                                              -3














                                                              !string.matches("a|b|c|d") 


                                                              works fine for me.






                                                              share|improve this answer





















                                                              • 6





                                                                Please give explanation / reason for better answer, It is too short

                                                                – sangram parmar
                                                                Nov 10 '16 at 10:14








                                                              • 1





                                                                How is this different from the accepted answer?

                                                                – Jiri Tousek
                                                                Nov 14 '16 at 12:24














                                                              -3












                                                              -3








                                                              -3







                                                              !string.matches("a|b|c|d") 


                                                              works fine for me.






                                                              share|improve this answer















                                                              !string.matches("a|b|c|d") 


                                                              works fine for me.







                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Nov 14 '16 at 10:50

























                                                              answered Nov 10 '16 at 10:09









                                                              BruBru

                                                              11




                                                              11








                                                              • 6





                                                                Please give explanation / reason for better answer, It is too short

                                                                – sangram parmar
                                                                Nov 10 '16 at 10:14








                                                              • 1





                                                                How is this different from the accepted answer?

                                                                – Jiri Tousek
                                                                Nov 14 '16 at 12:24














                                                              • 6





                                                                Please give explanation / reason for better answer, It is too short

                                                                – sangram parmar
                                                                Nov 10 '16 at 10:14








                                                              • 1





                                                                How is this different from the accepted answer?

                                                                – Jiri Tousek
                                                                Nov 14 '16 at 12:24








                                                              6




                                                              6





                                                              Please give explanation / reason for better answer, It is too short

                                                              – sangram parmar
                                                              Nov 10 '16 at 10:14







                                                              Please give explanation / reason for better answer, It is too short

                                                              – sangram parmar
                                                              Nov 10 '16 at 10:14






                                                              1




                                                              1





                                                              How is this different from the accepted answer?

                                                              – Jiri Tousek
                                                              Nov 14 '16 at 12:24





                                                              How is this different from the accepted answer?

                                                              – Jiri Tousek
                                                              Nov 14 '16 at 12:24


















                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10205437%2fcompare-one-string-with-multiple-values-in-one-expression%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              The term 'EXEC' is not recognized as the name of a cmdlet Powershell

                                                              NPM command prompt closes immediately [closed]

                                                              Error binding properties and functions in emscripten