示例 1: 检查 Int Array 是否包含给定值
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 中。
现在,我们使用 for-each loop 来遍历
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.
在上面的程序中,我们没有使用 for-each 循环,而是将数组转换为
IntStream
并使用它的
anyMatch()
方法。
anyMatch()
方法采用谓词、表达式或返回布尔值的函数。在我们的例子中,谓词将流中的每个元素
n 与
toFind 进行比较,并返回
true
或
false
。
如果任何元素
n 返回
true
,
found 也会设置为
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
并使用了
Arrays
的
stream()
方法来首先将其转换为流和
anyMatch()
以检查数组是否包含给定值
toFind。