3 façons de vérifier si une valeur existe dans un tableau en Java

En Java, il existe de nombreuses façons de vérifier si un élément particulier existe dans ce tableau.

1) Utilisez une méthode de recherche linéaire

Complexité temporelle : O(N) Espace auxiliaire : O(1)

pour (élément int : arr) {

    si (élément == toCheckValue) {

        retourner vrai ;

    }

}

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

résultat de l'opération :

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

Est-ce que 7 est présent dans le tableau : vrai

2 ) Utilisez la méthode List.contains()

La méthode List contains() en Java est utilisée pour vérifier si l'élément spécifié existe dans la liste donnée.

booléen public contient (objet)

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

résultat de l'opération :

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

Est-ce que 7 est présent dans le tableau : vrai

3 ) Utilisez la méthode Stream.anyMatch()

booléen anyMatch(Prédicat<T> prédicat)

T est le type d'entrée

La fonction renvoie vrai s'il y a des éléments, faux sinon.

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

résultat de l'opération :

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

Est-ce que 7 est présent dans le tableau : vrai

Je suppose que tu aimes

Origine blog.csdn.net/xijinno1/article/details/132114694
conseillé
Classement