Alfredo Bejarano Alfredo Bejarano - 4 months ago 15
Java Question

Most efficient way to check if an array contains a value in Java?

I have a similar logic for a method in a Java Class (not the real code, this is simplified for example purposes).

private Boolean method(Boolean booleanValue, SomeObject object) {
return booleanValue ? Arrays.asList(object.getStringsArray()).contains("string") : false;

A collaborator who assigned himself to check the PR gave the following comment:

This is inefficient. It is creating a new data structure only to iterate it and check if there is a certain string.

method returns a
, so will using a for-loop be better than

Which way is more efficient to achieve this?


Your co-worker is incorrect when they assert that your method is creating a new data structure.

If you look at the API for Arrays.asList(), it says that it

Returns a fixed-size list backed by the specified array.

There is no reason to write your own code to iterate over the array when you can just wrap a List around it, and use its built-in methods.