Java 程序:检查数组是否包含给定值

要理解此示例,您应了解以下Java编程主题


示例 1:检查整数数组是否包含给定值

class Main {
  public static void main(String[] args) {

    int[] num = {1, 2, 3, 4, 5};
    int toFind = 3;
    boolean found = false;

    for (int n : num) {
      if (n == toFind) {
        found = true;
        break;
      }
    }
    
    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}

输出

3 is found.

在上面的程序中,我们有一个存储在变量 num 中的整数数组。同样,要查找的数字存储在 toFind 中。

现在,我们使用一个 foreach循环 遍历 num 的所有元素,并单独检查 toFind 是否等于 n

如果相等,我们将 found 设置为 true 并从循环中跳出。如果不相等,我们继续下一次迭代。


示例 2:使用 Stream 检查数组是否包含给定值

import java.util.stream.IntStream;

class Main {
  public static void main(String[] args) {
    
    int[] num = {1, 2, 3, 4, 5};
    int toFind = 7;

    boolean found = IntStream.of(num).anyMatch(n -> n == toFind);

    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
      
  }
}

输出

7 is not found.

在上面的程序中,我们没有使用foreach循环,而是将数组转换为 IntStream,并使用其 anyMatch() 方法。

anyMatch() 方法接受一个谓词,一个表达式或一个返回布尔值的函数。在我们的例子中,谓词将流中的每个元素 ntoFind 进行比较,并返回 truefalse

如果任何一个元素 n 返回 truefound 也将被设置为 true


示例 3:检查非原始类型数组是否包含给定值

import java.util.Arrays;

class Main {
  public static void main(String[] args){

    String[] strings = {"One","Two","Three","Four","Five"};
    String toFind= "Four";

    boolean found = Arrays.stream(strings).anyMatch(t -> t.equals(toFind));

    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}

输出

Four is found.

在上面的程序中,我们使用了非原始数据类型 String,并使用 Arraysstream() 方法将其首先转换为流,然后使用 anyMatch() 检查数组是否包含给定的值 toFind

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战