Java Program To Check for an element in Array



Java Program To Check for an element in Array




Using For Loop:

package com.javainspires.examples;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ExampleMain {

    public static void main(String[] args) {

        //take a string array
        String[] names = {"Java","Python","Kotlin","Go"};

        String toFind = "Go";

        // using for loop
        for (String name : names) {
            if(toFind.equals(name)){
                System.out.println("Given array conatins "+toFind);
            }
        }
    }
}

Output:
Given array conatins Go

Using List Contains method:

package com.javainspires.examples;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ExampleMain {

    public static void main(String[] args) {

        //take a string array
        String[] names = {"Java", "Python", "Kotlin", "Go"};

        String toFind = "Go";

        // using List contains() method
        // convert array into string

        List<String> namesList = Arrays.asList(names);

        if (namesList.contains(toFind)) {
            System.out.println("Array contains " + toFind);
        } else {
            System.out.println("NA");
        }
    }
}

Output:
Array contains Go






Using Streams anyMatch method:

package com.javainspires.examples;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ExampleMain {

    public static void main(String[] args) {

        //take a string array
        String[] names = {"Java", "Python", "Kotlin", "Go"};

        String toFind = "Go";

        // using Stream anyMatch method
        // convert array to stream

        Stream<String> namesStream = Arrays.stream(names);
        if(namesStream.anyMatch(toFind::equals)){
            System.out.println("Array contains "+toFind);
        }else {
            System.out.println("NA");
        }
    }
}

Output:
Array contains Go

Using Binary Search in Array:

package com.javainspires.examples;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ExampleMain {

    public static void main(String[] args) {

        //take a string array
        String[] names = {"Java", "Python", "Kotlin", "Go"};

        String toFind = "Go";
        // using Binary Search in array
        // sort the array
        Arrays.sort(names);

        int index = Arrays.binarySearch(names,toFind);
        if(index >=0){
            System.out.println("Array contains "+toFind);
        }else {
            System.out.println("NA");
        }
    }
}

Output:
Array contains Go
















Post a Comment

Previous Post Next Post