广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >Java检查值是否存在于数组中的3种方法
  • 731
分享到

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

java算法 2023-09-17 19:09:14 731人浏览 泡泡鱼
摘要

在 Java 中,有许多方法可以检查此数组中是否存在特定元素。 1)使用线性搜索方法 时间复杂度:O(N) 辅助空间:O(1) for (int element : arr) {     if (elemen

在 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 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

来源地址:https://blog.csdn.net/xijinno1/article/details/132114694

--结束END--

本文标题: Java检查值是否存在于数组中的3种方法

本文链接: https://www.lsjlt.com/news/411314.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作