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

后端 未结 29 2729
予麋鹿
予麋鹿 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:45

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

    boolean found = false;  // class variable
    
    String search = "AB";
    Spliterator 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 spl = Arrays.spliterator( VALUES, 0, VALUES.length );
    …
    

提交回复
热议问题