How do I determine whether an array contains a particular value in Java?

后端 未结 29 2801
予麋鹿
予麋鹿 2020-11-21 05:00

I have a String[] with values like so:

public static final String[] VALUES = new String[] {\"AB\",\"BC\",\"CD\",\"AE\"};

Given

相关标签:
29条回答
  • 2020-11-21 05:43

    Create a boolean initially set to false. Run a loop to check every value in the array and compare to the value you are checking against. If you ever get a match, set boolean to true and stop the looping. Then assert that the boolean is true.

    0 讨论(0)
  • 2020-11-21 05:45

    the use of a Spliterator prevents the unnecessary generation of a List

    boolean found = false;  // class variable
    
    String search = "AB";
    Spliterator<String> spl = Arrays.spliterator( VALUES, 0, VALUES.length );
    while( (! found) && spl.tryAdvance(o -> found = o.equals( search )) );
    

    found == true if search is contained in the array


    this does work for arrays of primitives

    public static final int[] VALUES = new int[] {1, 2, 3, 4};
    boolean found = false;  // class variable
    
    int search = 2;
    Spliterator<Integer> spl = Arrays.spliterator( VALUES, 0, VALUES.length );
    …
    
    0 讨论(0)
  • 2020-11-21 05:47

    Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:

    public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");
    

    Then you can do (like above):

    STRINGS.contains("the string you want to find");
    
    0 讨论(0)
  • 2020-11-21 05:47

    Using a simple loop is the most efficient way of doing this.

    boolean useLoop(String[] arr, String targetValue) {
        for(String s: arr){
            if(s.equals(targetValue))
                return true;
        }
        return false;
    }
    

    Courtesy to Programcreek

    0 讨论(0)
  • 2020-11-21 05:49

    Concise update for Java SE 9

    Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.

    private static final Set<String> VALUES = Set.of(
        "AB","BC","CD","AE"
    );
    

    "Given String s, is there a good way of testing whether VALUES contains s?"

    VALUES.contains(s)
    

    O(1).

    The right type, immutable, O(1) and concise. Beautiful.*

    Original answer details

    Just to clear the code up to start with. We have (corrected):

    public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
    

    This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:

    private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
    

    (Note, you can actually drop the new String[]; bit.)

    Reference arrays are still bad and we want a set:

    private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
         new String[] {"AB","BC","CD","AE"}
    ));
    

    (Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)

    (*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)

    0 讨论(0)
  • 2020-11-21 05:49

    Developers often do:

    Set<String> set = new HashSet<String>(Arrays.asList(arr));
    return set.contains(targetValue);
    

    The above code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:

    Arrays.asList(arr).contains(targetValue);
    

    or

       for(String s: arr){
            if(s.equals(targetValue))
                return true;
        }
    
    return false;
    

    The first one is more readable than the second one.

    0 讨论(0)
提交回复
热议问题