Java method to judge whether a certain string is in the string array (4 types)

1. The most efficient (most primitive)

The code is as follows (example):

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));

    }

}

operation result:

2.List array Contains

The code is as follows (example):

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));

    }

}

operation result:

3. Set Contains

The code is as follows (example):

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));

    }

}

operation result:

4.Arrays的binarySearch

The code is as follows (example):

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));

    }

}

operation result:

Guess you like

Origin blog.csdn.net/xijinno1/article/details/131692680