$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,16,Arrays,3,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,21,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,74,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,52,Java 8 Difference,2,java 8 Stream Examples,1,Java 9,1,Java Conversions,12,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,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,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,13,String,57,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,9,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,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://1.bp.blogspot.com/-sOmQkjvDx70/Xv4DAqWSz1I/AAAAAAAACyQ/tHn8T4s7stQXJLGhn4kCACgFAIkehy5nQCLcBGAsYHQ/s640/Java%2B8%2BProgram%2BTo%2BCheck%2Bif%2Ba%2Bvalue%2Bis%2Bpresent%2Bin%2Ban%2BArray.png
https://1.bp.blogspot.com/-sOmQkjvDx70/Xv4DAqWSz1I/AAAAAAAACyQ/tHn8T4s7stQXJLGhn4kCACgFAIkehy5nQCLcBGAsYHQ/s72-c/Java%2B8%2BProgram%2BTo%2BCheck%2Bif%2Ba%2Bvalue%2Bis%2Bpresent%2Bin%2Ban%2BArray.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