Reputation: 511
Don't want to use loops. I tried the below code but it doesn't work for primitive types.
if ( Arrays.asList( myMatrix ).contains( -1 ) )
{
// do something
}
What shall be done here?
Upvotes: 1
Views: 3460
Reputation: 262534
Java should really have a method contains
on java.util.Arrays
.
Commons Lang has it, for example.
So I would either find it in the libraries I already use, or make a static helper method myself (with a simple loop inside).
Upvotes: 3
Reputation: 124235
You can't avoid iteration in your code since we need some way to test all elements in your array (at least until we will find the one we are looking for). But to make your life easier create some additional utility method like (name could be probably better/more descriptive) public static boolean contains(int[] array, int element)
which will handle iteration for us. Then simply use it like if(contains(matrix, -1))
.
In Java 8 you could use IntStream
which handles int[] myMatrix
array correctly (like Array.asList
handles Integer[] myMatrix
).
So as condition you could use something like:
IntStream.of(myMatrix).anyMatch(i -> i == -1)
Upvotes: 3
Reputation: 285405
"I don't want to use loops"
-- you can't always get what you want, and in fact in this situation, use a loop.
Upvotes: 2