In this tutorials I am going to show you how to check an array contains a specific value in Java 8.

Array contains a specific value :


import java.util.Arrays;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class Array_Contains {

    public static void main(String[] args) {
        
        int[] i = {10,20,30,40};
        boolean contains = IntStream.of(i).anyMatch(x -> x == 40);
        System.out.println("is int[] contains 40   : "+contains);
        
        double[] f = {1.2d,2.9d,3.0d,4.7d};
        boolean contains2 = DoubleStream.of(f).anyMatch(x -> x == 4.7d);
        System.out.println("is double[] contains 4.7d : "+contains2);
        
        long[] l = {198,165,78,140};
        boolean contains3 = LongStream.of(l).anyMatch(x -> x == 20);
        System.out.println("is long[] contains 20 : "+contains3);
        
        String[] s = new String[] {"AA","BB","CC","DD"};
        System.out.println("is String[] contains CD : "+Arrays.asList(s).contains("CD"));

    }

}

 

Output :

is int[] contains 40   : true
is double[] contains 4.7d : true
is long[] contains 20 : false
is String[] contains CD : false

Happy Learning 🙂