How can I check if all values in an array have a certain value?

前端 未结 2 1868
暖寄归人
暖寄归人 2021-01-16 17:08

In Java, given an array of values (say integers), is there a way to efficiently check to see if they all have a certain value?

For example, with an array of integers

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-16 17:41

    Or, if using java 8, you can do something like:

    if(Arrays.stream(numbers).allMatch(x -> x == 2)) {
        // do something
    }
    

    Basically, pretty much everything that you might want to do that deals with collections/arrays, can be very concisely done with the Streams.

提交回复
热议问题