陪玩平台源码,检查数组中是否存在特定元素的方法

陪玩平台源码,检查数组中是否存在特定元素的方法
在 Java 中,有许多方法可以检查此数组中是否存在特定元素。

一、使用线性搜索方法

时间复杂度: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

二、使用 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

三、使用 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

以上就是陪玩平台源码,检查数组中是否存在特定元素的方法, 更多内容欢迎关注之后的文章

posted @   云豹科技-苏凌霄  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
历史上的今天:
2023-02-08 视频直播系统源码,vue中captcha.js生成验证码
2023-02-08 在线直播源码,js获取滚动条的位置
2023-02-08 直播平台搭建,elementui的导航路由递归报错解决
2022-02-08 直播系统源代码,选择验证方式时选择邮箱验证
2022-02-08 短视频平台开发,查找日期和时间的数组
2022-02-08 直播源码网站,新用户登录时的注册页面和登录页面
点击右上角即可分享
微信分享提示