String/Object in Array Testing in Java – using Arrays.asList and Arrays.Stream Parallel

in blurt •  4 years ago 

This tutorial presents three ways of testing if a given element (integer, doubles, objects, strings) is in a given Array using Java programming language.

Java's Naive Implementation of Element (String) In Array Tests using Generic


In Java, if we want to test a given element in array, we can implement a naive version (let's take String for example):

private static boolean stringInArray1(String str, String[] arr) {
    for (var x: arr) {
        if (x.equals(str)) return true;
    }
    return false;
}

If we want to go with generic type, we can of course:

package com.helloacm;

public class Main<T> {
    private boolean inArray(T val, T[] arr) {
        for (T x: arr) {
            if (x.equals(val)) return true;
        }
        return false;
    }

    public static void main(String[] args)  {
        var arr = new String[] {"a", "ab", "abc", "abcde"};
        var test = new Main<String>();
        System.out.println(test.inArray(null, arr));
        System.out.println(test.inArray("adfasd", arr));
        System.out.println(test.inArray("a", arr));
    }
}

In-Array Test using Arrays.AsList().contains


We can convert the array type to List using Arrays.asList then in this case, we can simply use its contain method:

private boolean stringInArray1(T val, T[] arr) {
    return Arrays.asList(arr).contains(val);
}

Parallel version of Element-In-Array Tests using Arrays.Stream


Even better, we can convert the array to stream, then make a parallel version of the in-array test. It is cool, and it's potentially faster!

private boolean stringInArray1(T val, T[] arr) {
    return Arrays.stream(arr).
        parallel().
        anyMatch(s -> s.equals(val));
}

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Computing Technology


Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

Steem/Blurt On!~
Every little helps! I hope this helps!


If you like my work, please consider voting for me or Buy Me a Coffee, thanks!
https://steemit.com/~witnesses type in justyy and click VOTE



Alternatively, you could proxy to me if you are too lazy to vote!

Also: you can vote me at the tool I made: https://steemyy.com/witness-voting/?witness=justyy

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!