How To Check Array Contains Certain Value Java

In this example, I am showing How can I test if an array contains a certain value efficiently

In java 8 you can use Stream.of(array).anyMatch(x -> x == "world") for checking for string value (Example 1) .If it is integer value you can use IntStream.of(array2).anyMatch(x -> x == 0) (Example 2)

In java old version you can use Arrays.toString(array) to checking for string values (Example 3)

1) Java 8 Array Contains Certain String Value
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Test {

    public static void main(String[] args) throws IOException {

        // Check an array contains a certain value?
        String[] array = { "hello", "world" };

        System.out.println(Arrays.toString(array));
        
        // Java 8 string check
        System.out.println(Stream.of(array).anyMatch(x -> x == "world"));

    }
}

Output

[hello, world]
true

2) Java 8 Array Contains Certain Integer Value

import java.io.IOException;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Test {

    public static void main(String[] args) throws IOException {

        // Java 8 integer check
        int[] array2 = new int[5];
        System.out.println(IntStream.of(array2).anyMatch(x -> x == 0));
    }
}

Output

true


3) Java Array contains value for old versions

import java.io.IOException;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Test {

    public static void main(String[] args) throws IOException {

        // Check an array contains a certain value?
        String[] array = { "hello", "world" };

        System.out.println(Arrays.toString(array));
        
        // Java old way
        System.out.println(Arrays.asList(array).contains("world"));

    }
}

Output

[hello, world]
true














Your email address will not be published. Required fields are marked *