Is there a simpler way to check multiple values against one value in an if-statement?

前端 未结 12 762
名媛妹妹
名媛妹妹 2020-11-27 07:55

Basically, what I want to do is check two integers against a given value, therefore, classically what you would do is something like this:

//just to get some         


        
相关标签:
12条回答
  • 2020-11-27 07:57

    You could put the integers in a set and see if it contains the given value. Using Guava:

    if(newHashSet(a, b).contains(0)){
        // do something
    }
    

    But two simple int comparisons are probably easier to understand in this case.

    0 讨论(0)
  • 2020-11-27 07:57

    You can try this code:

    public static boolean match (Object ref, Object... objects)
    {
        if (ref == null)
            return false;
        //
        for (Object obj : objects)
            if (obj.equals (ref))
                return true;
        //
        return false;   
    }   //  match
    

    So if you can check this way:

    if (match (reference, "123", "124", "125"))
        ;   //  do something
    
    0 讨论(0)
  • 2020-11-27 08:00

    You can do the following in plain java

    Arrays.asList(a, b, c, d).contains(x);
    
    0 讨论(0)
  • 2020-11-27 08:00

    As referenced from this answer:

    In Java 8+, you might use a Stream and anyMatch. Something like

    if (Stream.of(b, c, d).anyMatch(x -> x.equals(a))) {
        // ... do something ...
    }
    

    Note that this has the chance of running slower than the other if checks, due to the overhead of wrapping these elements into a stream to begin with.

    0 讨论(0)
  • 2020-11-27 08:03

    Even if you have used the bit-wise operation as Ted suggested, the expressions are not equal, since one requires at least one of the variables to be zero and the second requires both of them to be zero.

    Regarding your question, there is no such shortcut in Java.

    0 讨论(0)
  • 2020-11-27 08:04

    There is no special syntax for that. You could make a function for that. Assuming at least Java 1.5:

    public <T> boolean eitherOneEquals(T o1, T o2, T expectedValue) {
      return o1.equals(expectedValue) || o2.equals(expectedValue);
    }
    
    if(eitherOneEquals(o1, o2, expectedValue)) {
       // do something...
    }
    
    0 讨论(0)
提交回复
热议问题