29

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

5 Answers 5

26

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

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thats pretty short, but this use case is common enough that they really should have added a function into the language
Be careful not to use that with primitive arrays.
@Casebash It compiles but doesn't do what you expect. Because of evil varargs, the argument gets treated as an array of arrays of primitives.
16

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'd need to do

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

if you're working with objects.

1 Comment

True, but if you're working with an ArrayList, doing boolean found = haystack.contains(needle) is much easier to read.
10

Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.

Comments

10

You might want to consider using a Collection implementation instead of a flat array.

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

ArrayList implementation defines an indexOf(Object o), which gives an index, but that method is not on all collection implementations.

Both these methods require proper implementations of the equals() method, and you probably want a properly implemented hashCode() method just in case you are using a hash based Collection (e.g. HashSet).

Comments

5

You can use one of the many Arrays.binarySearch() methods. Keep in mind that the array must be sorted first.

3 Comments

That's an option only is elements of array are comparable themselves.
We can only assume that this is the case, e.g. an array of ints, Strings, etc. You could always provide a custom Comparator to sort and search if needed.
hard to believe there's no Arrays.search ... <sigh>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.