Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

The getStringsArray() method returns a String[], so will using a for-loop be better than Arrays.asList()?

Which way is more efficient to achieve this?

like image 622
Alfredo Bejarano Avatar asked Jun 17 '16 16:06

Alfredo Bejarano


People also ask

How to check if a value is present in array in Java?

Check if a value is present in an Array in Java. Given an array, the task is to check whether a certain element is present in this Array or not, in Java. Examples: Input: arr[] = [5, 1, 1, 9, 7, 2, 6, 10], key = 7 Output: true Input: arr[] = [-1, 1, 5, 8], key = -2 Output: false. Below are various ways to do so: Using Linear Search Method:

How do I search an element in an array in Java?

Using core java we can search an element in an array in many ways. For searching in arrays of primitive or Objects, some methods are common for both and some can be used with in primitive type arrays. 1- For me most efficient method is using Arrays.binarySeach method.

How to check if an array contains an element in C++?

The standard library of C++ provides some algorithms and functions that we can use to check if an array contains an element in C++. But let us first see how we can use a loop to do this. You can use a for loop to keep things very simple. Here in the code below, we have an array called points and an element we have to search for named key.

How to check if a value is efficiently stored in an array/collection?

Actually, if you need to check if a value is contained in some array/collection efficiently, a sorted list or tree can do it in O (log (n)) or hashset can do it in O (1). If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags.


1 Answers

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.

like image 167
azurefrog Avatar answered Oct 05 '22 15:10

azurefrog