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
?
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.
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.
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.
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.
Arrays.asList(yourArray).contains(yourValue)
Warning: this doesn't work for arrays of primitives (see the comments).
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.
int[] a = {1,2,3,4}; boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With