3 ways to check if a value exists in an array in Java

In Java, there are many ways to check if a particular element exists in this array.

1) Use a linear search method

Time complexity: O(N) Auxiliary space: O(1)

for (int element : arr) {

    if (element == toCheckValue) {

        return true;

    }

}

Sample code:

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

operation result:

Array: [5, 1, 1, 9, 7, 2, 6, 10]

Is 7 present in the array: true

2 ) Use the List.contains() method

List contains() method in Java is used to check if the specified element exists in the given list.

public boolean contains(Object)

Sample code:

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

operation result:

Array: [5, 1, 1, 9, 7, 2, 6, 10]

Is 7 present in the array: true

3 ) Use the Stream.anyMatch() method

boolean anyMatch(Predicate<T> predicate)

T is the input type

The function returns true if there are any elements, false otherwise.

Sample code:

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

operation result:

Array: [5, 1, 1, 9, 7, 2, 6, 10]

Is 7 present in the array: true

Guess you like

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