I am downloading some data into a String array. Let's say ImageLinks
. How do I check if a item in array exist?
I am trying
if(ImageLinks[5] != null){}
but it gives me ArrayIndexOutOfBoundsException
. (Because there are really no 5 link in the array)
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.
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.
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.
To prevent the ArrayIndexOutOfBoundsException
, you can use the following:
if(ImageLinks.length > 5 && ImageLinks[5] != null) { // do something }
As the statements in the if
are checked from left to right, you won't reach the null check if the array doesn't have the correct size.
It's quite easy to generalise for any scenario.
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