$show=/label

Java 8 Program To Check if a value is present in an Array - Stream anyMatch() Example

SHARE:

A quick java program to check if a specific value is present in the array using Linear and Binary search approach and next contains() and Stream API anyMatch() method.

1. Introduction


In this tutorial, We'll be learning how to check whether a value is present in the array using linear and Binary search.

Next, using java methods such as contains() and Stream API anyMatch() method with primitive and String values.

Java 8 Program To Check if a value is present in an Array


Examples:

Input: arr[] = [6, 7, 10, 5, 70, 9], input 5
Output: true

Input: arr[] = [0, 8, -9, 56, 8], input = -5
Output: false



Check if a value is present in an Array in Java

2. Linear Search


In a linear search approach, each value in the array is compared with the given element.

package com.javaprogramto.arrays.find;

public class LinearSearch {

    public static void main(String[] args) {

        int[] array = {6, 7, 10, 5, 70, 9};

        boolean found = false;

        int valueToBeFound = 5;

        for(int value : array){

            if( value == valueToBeFound){
                found = true;
            }
        }

        if(found){
            System.out.println("value 5 is present");
        } else {
            System.out.println("value 5 is not present");
        }
    }
}

Output:

value 5 is present

3. Arrays Binary Search


Binary Search is another approach to check the value is in the list or array.

But, the input array must be sorted otherwise this logic will not work.

Arrays API has a binarySearch() method that returns a boolean value. If the array contains a value then true is returned.

package com.javaprogramto.arrays.find;

import java.util.Arrays;

public class BinarySearch {

    public static void main(String[] args) {

        int[] array = {6, 7, 10, 15, 70, 90};

        int found = -1;

        int valueToBeFound = 15;

        found = Arrays.binarySearch(array, valueToBeFound);

        if(found >= 0){
            System.out.println("value 15 is present");
        } else {
            System.out.println("value 15 is not present");
        }

        String[] names = {"ram", "sita", "zuga"};

        found = Arrays.binarySearch(names, "yama");


        if(found >= 0){
            System.out.println("String yama is present");
        } else {
            System.out.println("String yama is not present");
        }

    }
}

Output:

value 15 is present
String yama is not present

4. Contains() To Determine Whether an Array Contains a Particular Value in Java


package com.javaprogramto.arrays.find;

import java.util.Arrays;
import java.util.List;

public class ContainsExample {

    public static void main(String[] args) {

        Integer[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        List intList = Arrays.asList(values);

        if (intList.contains(7)) {
            System.out.println("7 is present in the values array");
        } else {
            System.out.println("7 is not present in the values array");
        }

        String[] fruites = {"banana", "jack fruit", "orange", "mango", "apple"};

        List fruitesList = Arrays.asList(fruites);

        if (fruitesList.contains("apple")) {
            System.out.println("apple is present in the fruitesList array");
        } else {
            System.out.println("apple is not present in the fruitesList array");
        }
    }
}

Output:

7 is present in the values array
apple is present in the fruitesList array

5. Java 8 anyMatch() to check array contains value or not


This is very easy to do in java 8 stream api. anyMatch() method is stream terminal operation.

First, Convert array into Stream and invoke anyMatch() method.

package com.javaprogramto.arrays.find;

import java.util.Arrays;

public class Java8AnyMatch {

    public static void main(String[] args) {

        Integer[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        boolean foundInt = Arrays.stream(values).anyMatch(value -> value == 6);

        if (foundInt) {
            System.out.println("6 is present in the values array using java 8 stream api using anyMatch() method");
        } else {
            System.out.println("6 is not present in the values array using java 8 stream api using anyMatch() method");
        }

        String[] fruites = {"banana", "jack fruit", "orange", "mango", "apple"};

        boolean foundFruit = Arrays.stream(fruites).anyMatch(fruitName -> "apple".equalsIgnoreCase(fruitName));

        if (foundFruit) {
            System.out.println("apple is present in the fruitesList array using java 8 stream api using anyMatch() method");
        } else {
            System.out.println("apple is not present in the fruitesList array using java 8 stream api using anyMatch() method");
        }
    }
}

Output:

6 is present in the values array using java 8 stream api using anyMatch() method
apple is present in the fruitesList array using java 8 stream api using anyMatch() method


In the similar way, you can check if array element is null in java 8 anyMatch() method.

6. Java 8 IntStream and Double Stream to Check value in Array


package com.javaprogramto.arrays.find;

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

public class IntDoubleStream {

    public static void main(String[] args) {

        int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        boolean foundInt = IntStream.of(values).anyMatch(value -> value == 6);

        if (foundInt) {
            System.out.println("value 8 check using IntStream anyMatch method.");
        } else {
            System.out.println("value 8 not found using IntStream");
        }


        double[] decimals = {1.1, 2.2, 3.3, 4.4, 5.5};

        boolean foundDouble = DoubleStream.of(decimals).anyMatch(value -> value == 5.5);

        if (foundDouble) {
            System.out.println("value 5.5 check using DoubleStream anyMatch method.");
        } else {
            System.out.println("value 5.5 not found using DoubleStream");
        }


    }
}

Output:

value 8 check using IntStream anyMatch method.
value 8 check using DoubleStream anyMatch method.

7. Conclusion


In this article, you've seen how to check value is present in the array or not. Various solutions are shown using the traditional approach and Java Streams concepts.

Read more on :

Java 8 Stream API
Convert Stream to IntStream

Ref
Mkyong

As usual, all programs shown are over GitHub.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Program To Check if a value is present in an Array - Stream anyMatch() Example
Java 8 Program To Check if a value is present in an Array - Stream anyMatch() Example
A quick java program to check if a specific value is present in the array using Linear and Binary search approach and next contains() and Stream API anyMatch() method.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXd7HnPxSr4ItJ5UMMY2DZKBZ_s6y_diaRFvFgRoDjLbyeMCRrM-pjbG40-kZ3L2VbKjWM4SH-1-BNiR1c1N1eFUhCFTVRC_gKCDEW0yIStFbnHRjD5sZ1rM9XxxnC30cS4phw2pU6zOY/s640/Java+8+Program+To+Check+if+a+value+is+present+in+an+Array.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXd7HnPxSr4ItJ5UMMY2DZKBZ_s6y_diaRFvFgRoDjLbyeMCRrM-pjbG40-kZ3L2VbKjWM4SH-1-BNiR1c1N1eFUhCFTVRC_gKCDEW0yIStFbnHRjD5sZ1rM9XxxnC30cS4phw2pU6zOY/s72-c/Java+8+Program+To+Check+if+a+value+is+present+in+an+Array.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/07/java-8-program-check-if-value-present-in-an-array.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/07/java-8-program-check-if-value-present-in-an-array.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content