当前位置: 首页 > news >正文

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

http://www.lryc.cn/news/109271.html

相关文章:

  • python 连接oracle pandas以简化excel的编写和数据操作
  • Kubernetes高可用集群二进制部署(三)部署api-server
  • 【网络|TCP】三次握手、四次握手
  • 刷题笔记 day7
  • Tuxera NTFS2023Mac强大的Mac读写工具
  • ARM64 常见汇编指令学习 11 -- ARM 汇编宏 .macro 的学习
  • 数据库的分库分表
  • [Docker实现测试部署CI/CD----相关服务器的安装配置(2)]
  • LC-980. 不同路径 III(回溯)
  • 软件测试缺陷报告
  • vue js-table2excel 导出excel 可带多张图片
  • HTML 基础标签
  • Nginx使用proxy_cache指令设置反向代理缓存静态资源
  • React安装ant design组件库,并使用
  • Leetcode | 有效的括号、最长有效括号
  • 思科模拟器配置静态路由(下一跳使用IP)
  • MyBatis -- 执行流程
  • springboot背诵
  • WebGL: 几个入门例子
  • App Cleaner Uninstaller for Mac 苹果电脑软件卸载工具
  • 基于Yolov2深度学习网络的车辆检测算法matlab仿真
  • Java的I/O类库- NIO
  • 【ASP.NET MVC】使用动软(三)(11)
  • 基于MATLAB长时间序列遥感数据植被物候提取与分析
  • K8S deployment 重启的三种方法
  • 解决Linux下PyCharm无法新建文件
  • 规则引擎技术解决方案
  • 2023奇安信天眼设备--面试题
  • 【剑指Offer 58】 左旋转字符串,Java解密。
  • Python SMTP发送邮件