csjoz11

导航

统计

Java检查值是否存在于数组中的3种方法

在 Java 中,有许多方法可以检查此数组中是否存在特定元素。

1)使用线性搜索方法
时间复杂度:O(N) 辅助空间:O(1)

for (int element : arr) {

    if (element == toCheckValue) {

        return true;

    }

}

示例代码:

import java.util.Arrays;
 
public class Demo {
    private static void check(int[] arr, int toCheckValue) {
        boolean test = false;
        for (int element : arr) {
            if (element == toCheckValue) {
                test = true;
                break;
            }
        }
        System.out.println("Is " + toCheckValue + " present in the array: " + test);
    }
 
    public static void main(String[] args) {
        int arr[] = {5, 1, 1, 9, 7, 2, 6, 10};
        int toCheckValue = 7;
        System.out.println("Array: " + Arrays.toString(arr));
        check(arr, toCheckValue);
    }
}
运行结果:

Array: [5, 1, 1, 9, 7, 2, 6, 10]

Is 7 present in the array: true

2)使用 List.contains() 方法
Java 中的 List contains() 方法用于检查指定元素是否存在于给定列表中。

public boolean contains(Object)

示例代码:

import java.util.Arrays;
 
public class Demo {
    private static void check(Integer[] arr, int toCheckValue) {
        boolean test = Arrays.asList(arr).contains(toCheckValue);
        System.out.println("Is " + toCheckValue + " present in the array: " + test);
    }
 
    public static void main(String[] args) {
        Integer arr[] = {5, 1, 1, 9, 7, 2, 6, 10};
        int toCheckValue = 7;
        System.out.println("Array: " + Arrays.toString(arr));
        check(arr, toCheckValue);
    }
}
运行结果:

Array: [5, 1, 1, 9, 7, 2, 6, 10]

Is 7 present in the array: true

3)使用 Stream.anyMatch() 方法
boolean anyMatch(Predicate<T> predicate)

T 是输入类型

如果有任何元素,则该函数返回 true , 否则为假。

示例代码:

import java.util.Arrays;
import java.util.stream.IntStream;
 
public class Demo {
    private static void check(int[] arr, int toCheckValue) {
        // 检查指定元素是否
        // 是否存在于数组中
        // 使用 anyMatch() 方法
        boolean test = IntStream.of(arr)
                .anyMatch(x -> x == toCheckValue);
 
        System.out.println("Is " + toCheckValue + " present in the array: " + test);
    }
 
    public static void main(String[] args) {
        int arr[] = {5, 1, 1, 9, 7, 2, 6, 10};
        int toCheckValue = 7;
        System.out.println("Array: " + Arrays.toString(arr));
        check(arr, toCheckValue);
    }
}
运行结果:

Array: [5, 1, 1, 9, 7, 2, 6, 10]

Is 7 present in the array: true
————————————————
版权声明:本文为CSDN博主「西晋的no1」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xijinno1/article/details/132114694

posted on   csjoz11  阅读(3832)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示