2740

I have a String[] with values like so:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

Given String s, is there a good way of testing whether VALUES contains s?

7
  • 6
    Long way around it, but you can use a for loop: "for (String s : VALUES) if (s.equals("MYVALUE")) return true;
    – Zack
    Commented Jul 15, 2009 at 0:51
  • 3
    @camickr--I have a nearly identical situation with this one: stackoverflow.com/a/223929/12943 It just keeps getting votes yet was just a copy/paste from sun's documentation. I guess score is based on how much help you provided and not how much effort you put into it--and mostly how fast you post it! Maybe we've stumbled onto John Skeet's secret! Well good answer, +1 for you.
    – Bill K
    Commented Apr 29, 2013 at 6:50
  • 3
    If you're using Apache Commons, then org.apache.commons.lang.ArrayUtils.contains() does this for you.
    – Mr. Boy
    Commented Nov 12, 2013 at 21:05
  • 51
    @camickr because people, like me, google a question, click on the SO result, see your answer, test it, it works, upvote the answer and then leave.
    – Aequitas
    Commented Jul 20, 2015 at 2:41
  • 3
    I really miss a simple indexOf and contains in java.util.Arrays - which would both contain straightforward loops. Yes, you can write those in 1 minute; but I still went over to StackOverflow expecting to find them somewhere in the JDK.
    – tucuxi
    Commented May 1, 2020 at 10:38

32 Answers 32

3409
Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


Since you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
32
  • 113
    I am somewhat curious as to the performance of this versus the searching functions in the Arrays class versus iterating over an array and using an equals() function or == for primitives. Commented Jul 15, 2009 at 0:06
  • 197
    You don't lose much, as asList() returns an ArrayList which has an array at its heart. The constructor will just change a reference so that's not much work to be done there. And contains()/indexOf() will iterate and use equals(). For primitives you should be better off coding it yourself, though. For Strings or other classes, the difference will not be noticeable.
    – Joey
    Commented Jul 15, 2009 at 0:09
  • 19
    Odd, NetBeans claims that 'Arrays.asList(holidays)' for an 'int[] holidays' returns a 'list<int[]>', and not a 'list<int>'. It just contains one single element. Meaning the Contains doesn't work since it just has one element; the int array.
    – Nyerguds
    Commented Nov 13, 2010 at 13:15
  • 67
    Nyerguds: indeed, this does not work for primitives. In java primitive types can't be generic. asList is declared as <T> List<T> asList(T...). When you pass an int[] into it, the compiler infers T=int[] because it can't infer T=int, because primitives can't be generic. Commented Jun 14, 2011 at 16:51
  • 31
    @Joey just a side note, it's an ArrayList, but not java.util.ArrayList as you expect, the real class returned is: java.util.Arrays.ArrayList<E> defined as: public class java.util.Arrays {private static class ArrayList<E> ... {}}.
    – TWiStErRob
    Commented Oct 17, 2012 at 9:16
457

Concise update for Java SE 9

Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.

private static final Set<String> VALUES = Set.of(
    "AB","BC","CD","AE"
);

"Given String s, is there a good way of testing whether VALUES contains s?"

VALUES.contains(s)

O(1).

The right type, immutable, O(1) and concise. Beautiful.*

Original answer details

Just to clear the code up to start with. We have (corrected):

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

(Note, you can actually drop the new String[]; bit.)

Reference arrays are still bad and we want a set:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));

(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)

(*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)

16
  • 204
    Except it's O(N) to create the collection in the first place :) Commented Apr 25, 2011 at 6:54
  • 69
    If it's static, it's probably going to be used quite a few times. So, the time consumed to initialise the set has good chances of being quite small compared to the cost of a lot of linear searches.
    – Xr.
    Commented Oct 12, 2011 at 19:39
  • 3
    @TomHawtin-tackline Why do you say "in particular here we want a set"? What is the advantage of a Set (HashSet) in this case? Why is a "reference array" bad (by "reference array" do you mean an ArrayList backed by an array as generated by a call to Arrays.asList)? Commented Aug 29, 2014 at 5:04
  • 7
    @nmr A TreeSet would be O(log n). HashSets are scaled such that the mean number of elements in a bucket is roughly constant. At least for arrays up to 2^30. There may be affects from, say, hardware caches which the big-O analysis ignores. Also assumes the hash function is working effectively. Commented Sep 9, 2014 at 23:51
  • 7
    This doesn't answer the question about the array. You just say "don't use arrays" which is not a solution. Additionally, you just say "X is bad" but don't explain why which is always bad for an answer.
    – Minn
    Commented Aug 18, 2019 at 20:37
246

You can use ArrayUtils.contains from Apache Commons Lang

public static boolean contains(Object[] array, Object objectToFind)

Note that this method returns false if the passed array is null.

There are also methods available for primitive arrays of all kinds.

Example:

String[] fieldsToInclude = { "id", "name", "location" };

if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
    // Do some stuff.
}
7
  • 4
    @max4ever I agree, but this is still better then "rolling your own" and easier to read then the raw java way.
    – Jason
    Commented Dec 7, 2012 at 17:48
  • 2
    package: org.apache.commons.lang.ArrayUtils
    – slamborne
    Commented Jan 31, 2014 at 2:39
  • 46
    @max4ever Sometimes you already have this library included (for other reasons) and it is a perfectly valid answer. I was looking for this and I already depend on Apache Commons Lang. Thanks for this answer.
    – GuiSim
    Commented Apr 22, 2014 at 19:30
  • 1
    Or you could just copy the method (and depedencies if there are any).
    – Buffalo
    Commented Mar 9, 2015 at 11:59
  • 12
    @max4ever Most android apps are minimalized by Proguard, putting only the classes and functions you need into your app. That makes it equal to roll your own, or copy the source of the apache thing. And whoever doesn't use that minimalization doesn't need to complain about 700kb or 78kb :) Commented Aug 12, 2016 at 13:11
167

Just simply implement it by hand:

public static <T> boolean contains(final T[] array, final T v) {
    for (final T e : array)
        if (e == v || v != null && v.equals(e))
            return true;

    return false;
}

Improvement:

The v != null condition is constant inside the method. It always evaluates to the same Boolean value during the method call. So if the input array is big, it is more efficient to evaluate this condition only once, and we can use a simplified/faster condition inside the for loop based on the result. The improved contains() method:

public static <T> boolean contains2(final T[] array, final T v) {
    if (v == null) {
        for (final T e : array)
            if (e == null)
                return true;
    } 
    else {
        for (final T e : array)
            if (e == v || v.equals(e))
                return true;
    }

    return false;
}
13
  • 9
    @Phoexo This solution is obviously faster because the accepted answer wraps the array into a list, and calls the contains() method on that list while my solution basically does what contains() only would do.
    – icza
    Commented Oct 10, 2012 at 11:25
  • 10
    @AlastorMoody e==v does a reference equality check which is very fast. If the same object (same by reference) is in the array, it will be found faster. If it is not the same instance, it still might be the same as claimed by the equals() method, this is what is checked if references are not the same.
    – icza
    Commented Jan 15, 2013 at 8:39
  • 25
    Why isn't this function part of Java? No wonder people say Java is bloated... look at all the answers above this that use a bunch of libraries when all you need is a for loop. Kids these days!
    – phreakhead
    Commented Apr 2, 2013 at 19:30
  • 4
    @phreakhead It is part of Java, see Collection.contains(Object)
    – Steve Kuo
    Commented Jan 11, 2014 at 0:37
  • 12
    @icza If you look at the source of Arrays and ArrayList it turns out that this isn't necessarily faster than the version using Arrays.asList(...).contains(...). Overhead of creating an ArrayList is extremely small, and ArrayList.contains() uses a smarter loop (actually it uses two different loops) than the one shown above (JDK 7).
    – Axel
    Commented Feb 11, 2014 at 7:41
98

Four Different Ways to Check If an Array Contains a Value

  1. Using List:

    public static boolean useList(String[] arr, String targetValue) {
        return Arrays.asList(arr).contains(targetValue);
    }
    
  2. Using Set:

    public static boolean useSet(String[] arr, String targetValue) {
        Set<String> set = new HashSet<String>(Arrays.asList(arr));
        return set.contains(targetValue);
    }
    
  3. Using a simple loop:

    public static boolean useLoop(String[] arr, String targetValue) {
        for (String s: arr) {
            if (s.equals(targetValue))
                return true;
        }
        return false;
    }
    
  4. Using Arrays.binarySearch():

    The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.

    public static boolean binarySearch(String[] arr, String targetValue) {  
        return Arrays.binarySearch(arr, targetValue) >= 0;
    }
    

Quick Example:

String testValue="test";
String newValueNotInList="newValue";
String[] valueArray = { "this", "is", "java" , "test" };
Arrays.asList(valueArray).contains(testValue); // returns true
Arrays.asList(valueArray).contains(newValueNotInList); // returns false
4
  • 5
    your binary search example should return a > 0; Commented Mar 27, 2015 at 1:33
  • 7
    Why? I think it should return a > -1, since 0 would indicate that it is contained at the head of the array.
    – mbelow
    Commented May 25, 2016 at 15:22
  • 4
    The first variant with (a >= 0) was correct, just check the docs, they say "Note that this guarantees that the return value will be >= 0 if and only if the key is found".
    – Yoory N.
    Commented Nov 30, 2017 at 13:08
  • Why works to String and not to int? static boolean exists(int[] ints, int k) { return Arrays.asList(ints).contains(k); } Commented May 21, 2019 at 20:57
76

If the array is not sorted, you will have to iterate over everything and make a call to equals on each.

If the array is sorted, you can do a binary search, there's one in the Arrays class.

Generally speaking, if you are going to do a lot of membership checks, you may want to store everything in a Set, not in an array.

2
  • 1
    Also, like I said in my answer, if you use the Arrays class, you can sort the array then perform the binary search on the newly sorted array. Commented Jul 15, 2009 at 0:10
  • 1
    @Thomas: I agree. Or you can just add everything into a TreeSet; same complexity. I would use the Arrays if it doesn't change (maybe save a little bit of memory locality since the references are located contiguously though the strings aren't). I would use the set if this would change over time.
    – Uri
    Commented Jul 15, 2009 at 0:14
54

For what it's worth I ran a test comparing the 3 suggestions for speed. I generated random integers, converted them to a String and added them to an array. I then searched for the highest possible number/string, which would be a worst case scenario for the asList().contains().

When using a 10K array size the results were:

Sort & Search   : 15
Binary Search   : 0
asList.contains : 0

When using a 100K array the results were:

Sort & Search   : 156
Binary Search   : 0
asList.contains : 32

So if the array is created in sorted order the binary search is the fastest, otherwise the asList().contains would be the way to go. If you have many searches, then it may be worthwhile to sort the array so you can use the binary search. It all depends on your application.

I would think those are the results most people would expect. Here is the test code:

import java.util.*;

public class Test {
    public static void main(String args[]) {
        long start = 0;
        int size = 100000;
        String[] strings = new String[size];
        Random random = new Random();

        for (int i = 0; i < size; i++)
            strings[i] = "" + random.nextInt(size);

        start = System.currentTimeMillis();
        Arrays.sort(strings);
        System.out.println(Arrays.binarySearch(strings, "" + (size - 1)));
        System.out.println("Sort & Search : "
                + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        System.out.println(Arrays.binarySearch(strings, "" + (size - 1)));
        System.out.println("Search        : "
                + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        System.out.println(Arrays.asList(strings).contains("" + (size - 1)));
        System.out.println("Contains      : "
                + (System.currentTimeMillis() - start));
    }
}
5
  • 6
    I don't understand this code. You sort the array 'strings' and use the same (sorted) array in both calls to binarySearch. How can that show anything except HotSpot runtime optimization? The same with the asList.contains call. You create a list from the sorted array and then does contains on it with the highest value. Of course it's going to take time. What is the meaning of this test? Not to mention being an improperly written microbenchmark
    – Erik
    Commented May 30, 2013 at 9:16
  • Also, since binary search can only be applied to a sorted set, sort and search is the only possible way to use binary search.
    – Erik
    Commented May 30, 2013 at 9:18
  • 1
    Sorting may have already been done for a number of other reasons, e.g., it could be sorted on init and never changed. There's use in testing search time on its own. Where this falls down however is in being a less than stellar example of microbenchmarking. Microbenchmarks are notoriously difficult to get right in Java and should for example include executing the test code enough to get hotspot optimisation before running the actual test, let alone running the actual test code more than ONCE with a timer. Example pitfalls
    – Vala
    Commented Oct 24, 2013 at 12:25
  • 9
    This test is flawed as it runs all 3 tests in the same JVM instance. The later tests could benefit from the earlier ones warming up the cache, JIT, etc
    – Steve Kuo
    Commented Jan 11, 2014 at 0:39
  • 6
    This test is actually totally unrelated. Sort & Search is linearithmic (n*log(n)) complexity, binary search is logarithmic and ArrayUtils.contains is obviously linear. It's no use to compare this solutions as they are in totally different complexity classes.
    – dragn
    Commented Sep 11, 2014 at 13:47
41

Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:

public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");

Then you can do (like above):

STRINGS.contains("the string you want to find");
40

With Java 8 you can create a stream and check if any entries in the stream matches "s":

String[] values = {"AB","BC","CD","AE"};
boolean sInArray = Arrays.stream(values).anyMatch("s"::equals);

Or as a generic method:

public static <T> boolean arrayContains(T[] array, T value) {
    return Arrays.stream(array).anyMatch(value::equals);
}
2
  • 4
    It's worth to also note the primitive specializations.
    – skiwi
    Commented Apr 7, 2014 at 20:11
  • To also add, anyMatch JavaDoc states that it "...May not evaluate the predicate on all elements if not necessary for determining the result.", so it may not need to continue processing after finding a match.
    – mkobit
    Commented Dec 15, 2014 at 17:21
29

You can use the Arrays class to perform a binary search for the value. If your array is not sorted, you will have to use the sort functions in the same class to sort the array, then search through it.

5
  • You can use the sort functions in the same class to accomplish that...I should add that to my answer. Commented Jul 15, 2009 at 0:06
  • 1
    Will probably cost more than the asList().contains() approach, then, I think. Unless you need to do that check very often (but if it's just a static list of values that can be sorted to begin with, to be fair).
    – Joey
    Commented Jul 15, 2009 at 0:10
  • True. There are a lot of variables as to which would be the most effective. It's good to have options though. Commented Jul 15, 2009 at 0:13
  • Some code that does this here: stackoverflow.com/a/48242328/9131078 Commented Jan 14, 2018 at 0:11
  • Sorting a whole array for a purpose of a search is expensive. We can use the same CPU time for the liner search itself. I prefer binary search on a collection which is already constructed in sorted order beforehand. Commented Feb 14, 2018 at 9:51
21

ObStupidAnswer (but I think there's a lesson in here somewhere):

enum Values {
    AB, BC, CD, AE
}

try {
    Values.valueOf(s);
    return true;
} catch (IllegalArgumentException exc) {
    return false;
}
1
  • 2
    Exception throwing is apparently heavy but this would be a novel way of testing a value if it works. The downside is that the enum has to be defined beforehand.
    – James P.
    Commented Jun 2, 2011 at 18:20
14

Actually, if you use HashSet<String> as Tom Hawtin proposed you don't need to worry about sorting, and your speed is the same as with binary search on a presorted array, probably even faster.

It all depends on how your code is set up, obviously, but from where I stand, the order would be:

On an unsorted array:

  1. HashSet
  2. asList
  3. sort & binary

On a sorted array:

  1. HashSet
  2. Binary
  3. asList

So either way, HashSet for the win.

1
  • 3
    HashSet membership should be O(1) and binary search on a sorted collection is O(log n). Commented Jul 3, 2014 at 17:21
14

Developers often do:

Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);

The above code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:

Arrays.asList(arr).contains(targetValue);

or

for (String s : arr) {
    if (s.equals(targetValue))
        return true;
}

return false;

The first one is more readable than the second one.

11

If you have the google collections library, Tom's answer can be simplified a lot by using ImmutableSet (http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)

This really removes a lot of clutter from the initialization proposed

private static final Set<String> VALUES =  ImmutableSet.of("AB","BC","CD","AE");
10

One possible solution:

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

public class ArrayContainsElement {
  public static final List<String> VALUES = Arrays.asList("AB", "BC", "CD", "AE");

  public static void main(String args[]) {

      if (VALUES.contains("AB")) {
          System.out.println("Contains");
      } else {
          System.out.println("Not contains");
      }
  }
}
10

In Java 8 use Streams.

List<String> myList =
        Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList.stream()
        .filter(s -> s.startsWith("c"))
        .map(String::toUpperCase)
        .sorted()
        .forEach(System.out::println);
0
7

Using a simple loop is the most efficient way of doing this.

boolean useLoop(String[] arr, String targetValue) {
    for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }
    return false;
}

Courtesy to Programcreek

3
  • This will throw a null pointer exception if the array contains a null reference before the target value. Commented Dec 21, 2015 at 2:45
  • 1
    the if statement should be : if (targetValue.equals(s)) because String equals has a instanceof checker.
    – TheArchon
    Commented May 3, 2016 at 1:37
  • use Objects.equals(obj1,obj2) instead to be null safe.
    – trilogy
    Commented Aug 2, 2019 at 17:12
6

the shortest solution
the array VALUES may contain duplicates
since Java 9

List.of(VALUES).contains(s);
2
  • Arrays.asList(VALUES).contains(s) will typically be more performant than List.of(VALUES).contains(s), since it's a view over the array and doesn't need to copy all the array values into a one-use list.
    – M. Justin
    Commented May 17, 2023 at 4:34
  • @M.Justin As you correctly stated: asList() wraps the original array VALUES with the List interface. List.of() returns an immutable list that is a copy of the original input array VALUES. For this reason, the original list can be changed w/o any side effects to the returned list.
    – Kaplan
    Commented May 17, 2023 at 20:47
6

Use the following (the contains() method is ArrayUtils.in() in this code):

ObjectUtils.java

public class ObjectUtils {
    /**
     * A null safe method to detect if two objects are equal.
     * @param object1
     * @param object2
     * @return true if either both objects are null, or equal, else returns false.
     */
    public static boolean equals(Object object1, Object object2) {
        return object1 == null ? object2 == null : object1.equals(object2);
    }
}

ArrayUtils.java

public class ArrayUtils {
    /**
     * Find the index of of an object is in given array,
     * starting from given inclusive index.
     * @param ts    Array to be searched in.
     * @param t     Object to be searched.
     * @param start The index from where the search must start.
     * @return Index of the given object in the array if it is there, else -1.
     */
    public static <T> int indexOf(final T[] ts, final T t, int start) {
        for (int i = start; i < ts.length; ++i)
            if (ObjectUtils.equals(ts[i], t))
                return i;
        return -1;
    }

    /**
     * Find the index of of an object is in given array, starting from 0;
     * @param ts Array to be searched in.
     * @param t  Object to be searched.
     * @return indexOf(ts, t, 0)
     */
    public static <T> int indexOf(final T[] ts, final T t) {
        return indexOf(ts, t, 0);
    }

    /**
     * Detect if the given object is in the given array.
     * @param ts Array to be searched in.
     * @param t  Object to be searched.
     * @return If indexOf(ts, t) is greater than -1.
     */
    public static <T> boolean in(final T[] ts, final T t) {
        return indexOf(ts, t) > -1;
    }
}

As you can see in the code above, that there are other utility methods ObjectUtils.equals() and ArrayUtils.indexOf(), that were used at other places as well.

0
6

Use below -

    String[] values = {"AB","BC","CD","AE"};
    String s = "A";
    boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));
1
  • I get "cannot resolve method 'contains(java.lang.String)' Commented Oct 31, 2023 at 23:41
5
  1. For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).

     Arrays.asList(...).contains(...)
    
  2. For fast performance if you repeatedly check against a larger set of elements

    • An array is the wrong structure. Use a TreeSet and add each element to it. It sorts elements and has a fast exist() method (binary search).

    • If the elements implement Comparable & you want the TreeSet sorted accordingly:

      ElementClass.compareTo() method must be compatable with ElementClass.equals(): see Triads not showing up to fight? (Java Set missing an item)

      TreeSet myElements = new TreeSet();
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
      // *Alternatively*, if an array is forceably provided from other code:
      myElements.addAll(Arrays.asList(myArray));
      
    • Otherwise, use your own Comparator:

      class MyComparator implements Comparator<ElementClass> {
           int compareTo(ElementClass element1; ElementClass element2) {
                // Your comparison of elements
                // Should be consistent with object equality
           }
      
           boolean equals(Object otherComparator) {
                // Your equality of comparators
           }
      }
      
      
      // construct TreeSet with the comparator
      TreeSet myElements = new TreeSet(new MyComparator());
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
    • The payoff: check existence of some element:

      // Fast binary search through sorted elements (performance ~ log(size)):
      boolean containsElement = myElements.exists(someElement);
      
1
  • 4
    Why bother with TreeSet? HashSet is faster (O(1)) and does not require ordering.
    – Sean Owen
    Commented Dec 30, 2013 at 9:53
5

If you don't want it to be case sensitive

Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);
4

Try this:

ArrayList<Integer> arrlist = new ArrayList<Integer>(8);

// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);

boolean retval = arrlist.contains(10);
if (retval == true) {
    System.out.println("10 is contained in the list");
}
else {
    System.out.println("10 is not contained in the list");
}
4

Check this

String[] VALUES = new String[]{"AB", "BC", "CD", "AE"};
String s;

for (int i = 0; i < VALUES.length; i++) {
    if (VALUES[i].equals(s)) {
        // do your stuff
    } else {
        //do your stuff
    }
}
1
  • 1
    This doesn't work - it will enter the else for every item that doesn't match (so if you're looking for "AB" in that array, it will go there 3 times, since 3 of the values aren't "AB"). Commented Jan 4, 2018 at 12:42
3

Arrays.asList() -> then calling the contains() method will always work, but a search algorithm is much better since you don't need to create a lightweight list wrapper around the array, which is what Arrays.asList() does.

public boolean findString(String[] strings, String desired){
   for (String str : strings){
       if (desired.equals(str)) {
           return true;
       }
   }
   return false; //if we get here… there is no desired String, return false.
}
0
2

Use Array.BinarySearch(array,obj) for finding the given object in array or not.

Example:

if (Array.BinarySearch(str, i) > -1)` → true --exists

false --not exists

3
  • 5
    Array.BinarySearch and Array.FindIndex are .NET methods and don't exist in Java.
    – ataylor
    Commented Jun 27, 2013 at 20:03
  • @ataylor there's Arrays.binarySearch in java. But you're right, no Arrays.findIndex
    – mente
    Commented Aug 28, 2013 at 7:27
  • 1
    It should be noted: The array must be sorted prior to making this call. If it is not sorted, the results are undefined. Commented Dec 19, 2019 at 21:17
2

Try using Java 8 predicate test method

Here is a full example of it.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Test {
    public static final List<String> VALUES =
            Arrays.asList("AA", "AB", "BC", "CD", "AE");

    public static void main(String args[]) {
        Predicate<String> containsLetterA = VALUES -> VALUES.contains("AB");
        for (String i : VALUES) {
            System.out.println(containsLetterA.test(i));
        }
    }
}

http://mytechnologythought.blogspot.com/2019/10/java-8-predicate-test-method-example.html

https://github.com/VipulGulhane1/java8/blob/master/Test.java

1

Create a boolean initially set to false. Run a loop to check every value in the array and compare to the value you are checking against. If you ever get a match, set boolean to true and stop the looping. Then assert that the boolean is true.

1

As I'm dealing with low level Java using primitive types byte and byte[], the best so far I got is from bytes-java https://github.com/patrickfav/bytes-java seems a fine piece of work

0

You can use Java Streams to determine whether an array contains a particular value. Here's an example:

import java.util.Arrays;

public class ArrayContainsValueExample {
    public static void main(String[] args) {
        String[] fruits = {"apple", "banana", "orange", "kiwi", "grape"};

        boolean containsOrange = Arrays.stream(fruits)
                .anyMatch("orange"::equals);

        if (containsOrange) {
            System.out.println("The array contains 'orange'");
        } else {
            System.out.println("The array does not contain 'orange'");
        }
    }
}

In the above example, we have an array of String type named fruits. We use the Arrays.stream() method to create a stream of the array elements. We then call the anyMatch() method to check if any of the elements in the stream match the value "orange". If any element matches the value, the anyMatch() method returns true, indicating that the array contains the value. If no element matches the value, the anyMatch() method returns false, indicating that the array does not contain the value.

Note that the anyMatch() method short-circuits, meaning that it stops processing the stream as soon as a match is found. This makes it efficient for large arrays, as it does not need to process all the elements.

Not the answer you're looking for? Browse other questions tagged or ask your own question.