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

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<String> set = new HashSet<String>(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));

    }

}

运行结果:

猜你喜欢

转载自blog.csdn.net/xijinno1/article/details/131692680