How to Check if an Array Contains a Value in Java Efficiently?

How to check if an array (unsorted) contains a certain value? This is a very useful and frequently used operation in Java. It is also a top voted question on Stack Overflow. As shown in top voted answers, this can be done in several different ways, but the time complexity could be very different. In the following I will show the time cost of each method.

1. 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():

binarySearch() can ONLY be used on sorted arrays. If the array is sorted, you can use the following code to search the target element:

public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
	int a =  Arrays.binarySearch(arr, targetValue);
	if(a > 0)
		return true;
	else
		return false;
}

2. Time Complexity

The approximate time cost can be measured by using the following code. The basic idea is to search an array of size 5, 1k, 10k. The approach may not be precise, but the idea is clear and simple.

public static void main(String[] args) {
	String[] arr = new String[] {  "CD",  "BC", "EF", "DE", "AB"};
 
	//use list
	long startTime = System.nanoTime();
	for (int i = 0; i < 100000; i++) {
		useList(arr, "A");
	}
	long endTime = System.nanoTime();
	long duration = endTime - startTime;
	System.out.println("useList:  " + duration / 1000000);
 
	//use set
	startTime = System.nanoTime();
	for (int i = 0; i < 100000; i++) {
		useSet(arr, "A");
	}
	endTime = System.nanoTime();
	duration = endTime - startTime;
	System.out.println("useSet:  " + duration / 1000000);
 
	//use loop
	startTime = System.nanoTime();
	for (int i = 0; i < 100000; i++) {
		useLoop(arr, "A");
	}
	endTime = System.nanoTime();
	duration = endTime - startTime;
	System.out.println("useLoop:  " + duration / 1000000);
}

Result:

useList:  13
useSet:  72
useLoop:  5

Use a larger array (1k):

String[] arr = new String[1000];
 
Random s = new Random();
for(int i=0; i< 1000; i++){
	arr[i] = String.valueOf(s.nextInt());
}

Result:

useList:  112
useSet:  2055
useLoop:  99
useArrayBinary:  12

Use a larger array (10k):

String[] arr = new String[10000];
 
Random s = new Random();
for(int i=0; i< 10000; i++){
	arr[i] = String.valueOf(s.nextInt());
}

Result:

useList:  1590
useSet:  23819
useLoop:  1526
useArrayBinary:  12

Clearly, using a simple loop method is more efficient than using any collection. A lot of developers use the first method, but it is inefficient. Pushing the array to another collection requires spin through all elements to read them in before doing anything with the collection type.

The array must be sorted, if Arrays.binarySearch() method is used. In this case, the array is not sorted, therefore, it should not be used.

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).

Related posts:

  1. ArrayList vs. LinkedList vs. Vector
  2. HashSet vs. TreeSet vs. LinkedHashSet
  3. Efficient Counter in Java
  4. LeetCode – Search in Rotated Sorted Array (Java)

Category >> Array >> Java   If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:

<pre><code>
String foo = "bar";
</code></pre>
  • Brandy Knapp Smallwood

    try this for(x=0;10>x;x++) { any code here}

    it will repeat


  • wenchao

    hashset can do it in O(1)? Why in your case, hastset is the slowest?


  • I dont know

    Is there a way to say “ignore case” while using

    Arrays.asList(arr).contains(targetValue)


  • Anttix

    Profiling with simple loops does not yield meaningful results.

    JVMs are smart and can optimize out code that produces data which is not consumed.

    Also the is the state of JIT caches, the garbage collector runs and other considerations.

    The bottom line is that in order to get meaningful results for small
    snippets you need to use a more elaborate benchmarking harness. e.g.
    JMH. See this excellent talk about benchmarking below

    http://shipilev.net/talks/devoxx-Nov2013-benchmarking.pdf

原文地址:https://www.cnblogs.com/qinblog/p/10181639.html

时间: 2024-10-01 09:56:17

How to Check if an Array Contains a Value in Java Efficiently?的相关文章

[ES2016] Check if an array contains an item using Array.prototype.includes

We often want to check if an array includes a specific item. It's been common to do this with the Array.prototype.indexOf method, but now we have a simpler way: We can use the Array.prototype.includes method, which is available starting with ES2016.

leetcode 108 Convert Sorted Array to Binary Search Tree ----- java

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 给一个排好序的数组,然后求搜索二叉树 其实就是二分法,不难. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNo

Java – Check if Array contains a certain value?

Java – Check if Array contains a certain value?1. String Arrays1.1 Check if a String Array contains a certain value "A". StringArrayExample1.javapackage com.mkyong.core; import java.util.Arrays;import java.util.List; public class StringArrayExam

【翻译】Java Array的排名前十方法(Top 10 Methods for Java Arrays)

这里列举了Java Array 的前十的方法.他们在stackoverflow最大投票的问题. The following are top 10 methods for Java Array. They are the most voted questions from stackoverflow. 0.声明一个数组 0. Declare an array String[] aArray = new String[5]; String[] bArray = {"a", "b&

Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final) D. Array Restoration

D. Array Restoration time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output Initially there was an array aa consisting of nn integers. Positions in it are numbered from 11 to nn. Exactly qq querie

Scala学习之Tuple、Map、Array

1.Tuple Tuple的中文意思是元组,它的定义是不需要方法. 例如:val tup=(25,”Tuple”,”Map”,”Array”). 值得注意的是,Tuple在进行索引的时候,与我们平时所见到的数组是有很多不同点的,它的索引方式是通过:下划线和一个基于1的元素索引.(这里特别强调基数,因为在Java.C++中,我们定义数组的时候,都是基于0开始的) object TupleOps {   def main(args:Array[String]): Unit={     val tup

分享非常有用的Java程序 (关键代码)(五)---把 Array 转换成 Map

原文:分享非常有用的Java程序 (关键代码)(五)---把 Array 转换成 Map import java.util.Map; import org.apache.commons.lang.ArrayUtils; public class Main { public static void main(String[] args) { String[][] countries = { { "United States", "New York" }, { &quo

Java for LeetCode 081 Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. 解题思路: 参考Java for LeetCode 033 Search in Rota

Adding New Functions to MySQL(User-Defined Function Interface UDF、Native Function)

catalog 1. How to Add New Functions to MySQL 2. Features of the User-Defined Function Interface 3. User-Defined Function 4. UDF Argument Processing 5. UDF Return Values and Error Handling 6. UDF Compiling and Installing 7. Adding a New Native Functio