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

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

    Check this

    String[] VALUES = new String[] {"AB","BC","CD","AE"};
    String s;
    
    for(int i=0; i< VALUES.length ; i++)
    {
        if ( VALUES[i].equals(s) )
        { 
            // do your stuff
        } 
        else{    
            //do your stuff
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:37

    Use Array.BinarySearch(array,obj) for finding the given object in array or not.

    Example:

    if (Array.BinarySearch(str, i) > -1)` → true --exists
    

    false --not exists

    0 讨论(0)
  • 2020-11-21 05:38
    Arrays.asList(yourArray).contains(yourValue)
    

    Warning: this doesn't work for arrays of primitives (see the comments).


    Since java-8 you can now use Streams.

    String[] values = {"AB","BC","CD","AE"};
    boolean contains = Arrays.stream(values).anyMatch("s"::equals);
    

    To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

    Example

    int[] a = {1,2,3,4};
    boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
    
    0 讨论(0)
  • 2020-11-21 05:38

    In Java 8 use Streams.

    List<String> myList =
    Arrays.asList("a1", "a2", "b1", "c2", "c1");
    
    myList
    .stream()
    .filter(s -> s.startsWith("c"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);
    
    0 讨论(0)
  • 2020-11-21 05:39

    Use the following (the contains() method is ArrayUtils.in() in this code):

    ObjectUtils.java

    public class ObjectUtils{
    
        /**
         * A null safe method to detect if two objects are equal.
         * @param object1
         * @param object2
         * @return true if either both objects are null, or equal, else returns false.
         */
        public static boolean equals(Object object1, Object object2){
            return object1==null ? object2==null : object1.equals(object2);
        }
    
    }
    

    ArrayUtils.java

    public class ArrayUtils{
    
        /**
         * Find the index of of an object is in given array, starting from given inclusive index.
         * @param ts  Array to be searched in.
         * @param t  Object to be searched.
         * @param start  The index from where the search must start.
         * @return Index of the given object in the array if it is there, else -1.
         */
        public static <T> int indexOf(final T[] ts, final T t, int start){
            for(int i = start; i < ts.length; ++i)
                if(ObjectUtils.equals(ts[i], t))
                    return i;
            return -1;
        }
    
        /**
         * Find the index of of an object is in given array, starting from 0;
         * @param ts  Array to be searched in.
         * @param t  Object to be searched.
         * @return  indexOf(ts, t, 0)
         */
        public static <T> int indexOf(final T[] ts, final T t){
            return indexOf(ts, t, 0);
        }
    
        /**
         * Detect if the given object is in the given array.
         * @param ts  Array to be searched in.
         * @param t  Object to be searched.
         * @return  If indexOf(ts, t) is greater than -1.
         */
        public static <T> boolean in(final T[] ts, final T t){
            return indexOf(ts, t) > -1 ;
        }
    
    }
    

    As you can see in the code above, that there are other utility methods ObjectUtils.equals() and ArrayUtils.indexOf(), that were used at other places as well.

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

    For what it's worth I ran a test comparing the 3 suggestions for speed. I generated random integers, converted them to a String and added them to an array. I then searched for the highest possible number/string, which would be a worst case scenario for the asList().contains().

    When using a 10K array size the results were:

    Sort & Search   : 15
    Binary Search   : 0
    asList.contains : 0
    

    When using a 100K array the results were:

    Sort & Search   : 156
    Binary Search   : 0
    asList.contains : 32
    

    So if the array is created in sorted order the binary search is the fastest, otherwise the asList().contains would be the way to go. If you have many searches, then it may be worthwhile to sort the array so you can use the binary search. It all depends on your application.

    I would think those are the results most people would expect. Here is the test code:

    import java.util.*;
    
    public class Test
    {
        public static void main(String args[])
        {
            long start = 0;
            int size = 100000;
            String[] strings = new String[size];
            Random random = new Random();
    
    
            for (int i = 0; i < size; i++)
                strings[i] = "" + random.nextInt( size );
    
            start = System.currentTimeMillis();
            Arrays.sort(strings);
            System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
            System.out.println("Sort & Search : " + (System.currentTimeMillis() - start));
    
            start = System.currentTimeMillis();
            System.out.println(Arrays.binarySearch(strings, "" + (size - 1) ));
            System.out.println("Search        : " + (System.currentTimeMillis() - start));
    
            start = System.currentTimeMillis();
            System.out.println(Arrays.asList(strings).contains( "" + (size - 1) ));
            System.out.println("Contains      : " + (System.currentTimeMillis() - start));
        }
    }
    
    0 讨论(0)
提交回复
热议问题