在此程序中,您将学习Java中检查数组是否包含给定值。
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 + " 找到");
else
System.out.println(toFind + " 未找到");
}
}
运行该程序时,输出为:
3 找到
在上面的程序中,我们有一个存储在变量num中的整数数组。 同样,要查找的数字存储在toFind中
现在,我们使用一个foreach循环遍历num的所有元素,并分别检查toFind是否等于n
如果是,我们将find设置为true并退出循环。 如果不是,我们转到下一个迭代
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 + " 找到");
else
System.out.println(toFind + " 未找到");
}
}
运行该程序时,输出为:
7 未找到
在上面的程序中,我们没有使用foreach循环,而是将数组转换为IntStream并使用其anyMatch()方法
anyMatch()方法采用谓词,表达式或返回布尔值的函数。 在我们的实例中,谓词将流中的每个元素n与toFind进行比较,并返回true或false
如果元素n中的任何一个返回true,则found也将设置为true
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 + " 找到");
else
System.out.println(toFind + " 未找到");
}
}
运行该程序时,输出为:
Four 找到
在上面的程序中,我们使用了非原始数据类型String,并使用了Arrays的stream()方法首先将其转换为流,并使用anyMatch()来检查数组是否包含给定值toFind