简体   繁体   中英

Checking if an array contains one integer value

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?

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)

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).

"I don't want to use loops" -您不能总是得到想要的东西,实际上在这种情况下,请使用循环。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM