Java 8 Array Contains – How to check if array contains certain value using stream API

4 weeks ago Lalit Bhagtani 0

Java 8 Array Contains

In this tutorial, we will learn about how to check if array contains certain value or not in Java 8 using Stream API.

JavaArrayContains

Problem Statement

Given an array of string and int data type, check if array contains “a” and 1 in their respective arrays or not. To implement this, we will use Stream Class of Stream API.

import java.util.stream.IntStream;
import java.util.stream.Stream;

public class ArrayContains {
	
  public static void main(String[] args) {
		
    // Object Array example using String array
		
    /* Create a new String array */
    String[] strArray = new String[] {"a", "b", "c", "d", "e"};
		
    /* Create Stream of String Array */
    /* Invoke anyMatch method to check if array contains "a" */
    Boolean result = Stream.of(strArray).anyMatch("a"::equals);
		
    System.out.println(result);
		
    // Primitive Array example using int array
		
    /* Create a new int array */
    int[] intArray = new int[] {1, 2, 3, 4, 5};
		
    /* Create IntStream of int Array */
    /* Invoke anyMatch method to check if array contains 1 */		
    Boolean intResult = IntStream.of(intArray).anyMatch( e -> e == 1);
		
    System.out.println(result);
		
  }

}

Result :- 

true
true

References :- 

  1. IntStream JavaDocs
  2. Stream JavaDocs

That’s all for how to check if array contains certain value or not in Java 8 using Stream API. If you liked it, please share your thoughts in comments section and share it with others too.

Next