Finding an element in an array in Java

Does Java have a built-in function that allows me to linearly search for an element in an array, or do I just need to use a for loop?

+16
java arrays
Aug 01 '10 at 23:55
source share
5 answers

There is a contains method for lists, so you should be able to:

 Arrays.asList(yourArray).contains(yourObject); 

Warning: this may not do what you (or I) expect, see Tom's comment below.

+15
Aug 2 2018-10-10T00: 00Z
source share

You might want to use the Collection implementation instead of a flat array.

The Collection interface defines a contains(Object o) method that returns true / false .

ArrayList implementation defines indexOf(Object o) , which gives an index, but this method does not apply to all implementations of the collection.

Both of these methods require proper implementations of the equals() method, and you probably need a properly implemented hashCode() method if you use a Collection based hash (e.g. HashSet ).

+7
Aug 02 '10 at 0:00
source share

With Java 8, you can do this:

 int[] haystack = {1, 2, 3}; int needle = 3; boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle); 

You will need to do

 boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x)); 

if you work with objects.

+7
May 15 '15 at 3:51
source share

Use the for loop. There is nothing built into the array. Or switch to the java.util Collection collection class.

+5
Aug 01 '10 at 23:59
source share

You can use one of the Arrays.binarySearch() methods. Keep in mind that you must first sort the array.

+3
Aug 2 2018-10-10T00: 00Z
source share



All Articles