Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

I have a String[] with values like so:

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

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

like image 857
Mike Sickler Avatar asked Jul 15 '09 00:07

Mike Sickler


People also ask

How do you check if an array has a certain value?

For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.

How do you check if an array contains a certain element in Java?

contains() method in Java? The ArrayList. contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it​.

How do you check if an array does not contain a value JAVA?

To check if an array doesn't include a value, use the logical NOT (!) operator to negate the call to the includes() method. The NOT (!) operator returns false when called on a true value and vice versa.

How do you check if an array contains a string in Java?

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.


1 Answers

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); 
like image 110
camickr Avatar answered Sep 23 '22 02:09

camickr