Java 8 Array contains a specific value ?

By | 2018-03-03T07:44:00+00:00 December 4th, 2017|java8|0 Comments

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment