如何检查数组中的所有值是否具有特定值? [英] How can I check if all values in an array have a certain value?

查看:91
本文介绍了如何检查数组中的所有值是否具有特定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,给定一个值数组(比如整数),有没有办法有效地检查它们是否都有一定值?

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 such as:

int[] numbers = {2, 2, 2, 2, 2, 2, 2};

并且只有当所有这些都是2时才需要执行操作,是否有更有效的方法比这样做:

and you need to perform an action only if all of them are 2, is there a more effective way than doing this:

if (numbers[1] == 2 && numbers[2] == 2 && numbers[3] == 2 && …)

我知道有办法在C ++中这样做但是Java呢?

I know there are ways to do this in C++ but what about Java?

推荐答案

用于所有Java版本:

For use on all Java versions:

public static boolean allMatch(int[] array, int value) {
    for (int i = 0; i < array.length; i++)
        if (array[i] != value)
            return false;
    return true;
}

像这样使用:

if (allMatch(numbers, 2)) {
    // do something
}

对于Java 8+(Bhashit Parikh的回答被盗):

For Java 8+ (stolen from answer by Bhashit Parikh):

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

这篇关于如何检查数组中的所有值是否具有特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆