Javaで配列に値が存在するかどうかを確認する3つの方法

Java では、この配列に特定の要素が存在するかどうかを確認する方法がたくさんあります。

1) 線形探索法を使用する

時間計算量: O(N) 補助空間: O(1)

for (int要素: arr) {

    if (要素 == toCheckValue) {

        true を返します。

    }

}

サンプルコード:

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

操作結果:

配列: [5、1、1、9、7、2、6、10]

配列に 7 が存在するかどうか: true

2 ) List.contains() メソッドを使用する

Java の List contains() メソッドは、指定された要素が指定されたリストに存在するかどうかを確認するために使用されます。

public boolean contains(Object)

サンプルコード:

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

操作結果:

配列: [5、1、1、9、7、2、6、10]

配列に 7 が存在するかどうか: true

3 ) Stream.anyMatch() メソッドを使用する

boolean anyMatch(Predicate<T> 述語)

T は入力タイプです

この関数は、要素がある場合は true を返し、要素がない場合は false を返します。

サンプルコード:

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

操作結果:

配列: [5、1、1、9、7、2、6、10]

配列に 7 が存在するかどうか: true

おすすめ

転載: blog.csdn.net/xijinno1/article/details/132114694