原文: https://www.programiz.com/java-programming/examples/array-contains-value
在此程序中,您将学习检查数组是否包含 Java 中的给定值。
示例 1:检查Int数组是否包含给定值
public class Contains {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.");elseSystem.out.println(toFind + " is not found.");}}
运行该程序时,输出为:
3 is found.
在上面的程序中,我们有一个整数数组,存储在变量num中。 同样,要找到的编号存储在toFind中。
现在,我们使用foreach循环遍历num的所有元素,并分别检查toFind是否等于n。
如果是,我们将found设置为true,然后退出循环。 如果不是,我们转到下一个迭代。
示例 2:使用Stream检查数组是否包含给定值
import java.util.stream.IntStream;public class Contains {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.");elseSystem.out.println(toFind + " is not found.");}}
运行该程序时,输出为:
7 is not found.
在上面的程序中,我们没有使用foreach循环,而是将数组转换为IntStream并使用其anyMatch()方法。
anyMatch()方法采用返回布尔值的谓词,表达式或函数。 在我们的情况下,谓词将流中的每个元素n与toFind进行比较,然后返回true或false。
如果元素n中的任何一个返回true,则将toFind设置为true。
示例 3:检查数组是否包含非原始类型的给定值
import java.util.Arrays;public class Contains {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.");elseSystem.out.println(toFind + " is not found.");}}
运行该程序时,输出为:
Four is found.
在上面的程序中,我们使用了非原始数据类型String,并使用Arrays的stream()方法首先将其转换为流,然后使用anyMatch()检查数组是否包含给定值toFind。
