广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >java判断某个字符串是否在字符串数组中的方法(4种)
  • 688
分享到

java判断某个字符串是否在字符串数组中的方法(4种)

java 2023-09-05 13:09:30 688人浏览 泡泡鱼
摘要

1.效率最高(最原始) 代码如下(示例): public class Demo {     public static boolean useLoop(String[] arr, String targetValue) {

1.效率最高(最原始)

代码如下(示例):

public class Demo {

    public static boolean useLoop(String[] arr, String targetValue) {

        for (String s : arr) {

            if (s.equals(targetValue)) return true;

        }

        return false;

    }

 

    public static void main(String[] args) {

        String arr[] = {"aa", "bb", "cc"};

        String targetValue = "bb";

        System.out.println(useLoop(arr, targetValue));

    }

}

运行结果:

2.List数组Contains

代码如下(示例):

import java.util.Arrays;

 

public class Demo {

    public static boolean useList(String[] arr, String targetValue) {

        return Arrays.asList(arr).contains(targetValue);

    }

 

    public static void main(String[] args) {

        String arr[] = {"aa", "bb", "cc"};

        String targetValue = "bb";

        System.out.println(useList(arr, targetValue));

    }

}

运行结果:

3.Set的Contains

代码如下(示例):

import java.util.Arrays;

import java.util.HashSet;

import java.util.Set;

 

public class Demo {

    public static boolean useSet(String[] arr, String targetValue) {

        Set set = new HashSet(Arrays.asList(arr));

        return set.contains(targetValue);

    }

 

    public static void main(String[] args) {

        String arr[] = {"aa", "bb", "cc"};

        String targetValue = "bb";

        System.out.println(useSet(arr, targetValue));

    }

}

运行结果:

4.Arrays的binarySearch

代码如下(示例):

import java.util.Arrays;

 

public class Demo {

    public static boolean useArraysBinarySearch(String[] arr, String targetValue) {

        int a = Arrays.binarySearch(arr, targetValue);

        if (a > 0) {

            return true;

        } else {

            return false;

        }

    }

 

    public static void main(String[] args) {

        String arr[] = {"aa", "bb", "cc"};

        String targetValue = "bb";

        System.out.println(useArraysBinarySearch(arr, targetValue));

    }

}

运行结果:

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

--结束END--

本文标题: java判断某个字符串是否在字符串数组中的方法(4种)

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

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

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

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

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

  • 微信公众号

  • 商务合作