3 Möglichkeiten, um zu überprüfen, ob ein Wert in einem Array in Java vorhanden ist

In Java gibt es viele Möglichkeiten zu überprüfen, ob ein bestimmtes Element in diesem Array vorhanden ist.

1) Verwenden Sie eine lineare Suchmethode

Zeitkomplexität: O(N) Hilfsraum: O(1)

for (int element : arr) {

    if (element == toCheckValue) {

        return true;

    }

}

Beispielcode:

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

Operationsergebnis:

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

Ist 7 im Array vorhanden: wahr

2 ) Verwenden Sie die Methode List.contains()

Die Methode „Liste enthält()“ in Java wird verwendet, um zu überprüfen, ob das angegebene Element in der angegebenen Liste vorhanden ist.

öffentlicher boolescher Wert enthält (Objekt)

Beispielcode:

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

Operationsergebnis:

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

Ist 7 im Array vorhanden: wahr

3 ) Verwenden Sie die Stream.anyMatch()-Methode

boolean anyMatch(Predicate<T> predicate)

T ist der Eingabetyp

Die Funktion gibt true zurück, wenn Elemente vorhanden sind, andernfalls false.

Beispielcode:

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

Operationsergebnis:

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

Ist 7 im Array vorhanden: wahr

Ich denke du magst

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