Which Java Method Is Fastest to Check If an Array Contains a Value?
This article compares several Java techniques—using List, Set, a simple loop, Arrays.binarySearch, and Apache Commons ArrayUtils—to determine whether an unordered array contains a specific value, analyzes their time complexities, and presents benchmark results for arrays of different sizes.
How to check whether an unordered array contains a specific value in Java, a common and useful operation.
Using List
public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); }Using Set
public static boolean useSet(String[] arr, String targetValue) { Set<String> set = new HashSet<>(Arrays.asList(arr)); return set.contains(targetValue); }Using Loop
public static boolean useLoop(String[] arr, String targetValue) { for (String s : arr) { if (s.equals(targetValue)) return true; } return false; }Using Arrays.binarySearch()
Arrays.binarySearch() works only on sorted arrays; using it on an unsorted array yields unpredictable results.
For sorted arrays the method can be used as follows:
public static boolean useArraysBinarySearch(String[] arr, String targetValue) { int a = Arrays.binarySearch(arr, targetValue); return a > 0; }Performance tests were run on arrays of size 5, 1 k, and 10 k. The simple loop was consistently the fastest, while converting the array to a collection (List or Set) added overhead. Binary search is only applicable to sorted data and offers O(log n) time.
Using Apache Commons ArrayUtils
The ArrayUtils.contains method provides a convenient wrapper but internally uses a loop.
public static boolean useArrayUtils(String[] arr, String targetValue) { return ArrayUtils.contains(arr, targetValue); }Benchmarks show its speed lies between the loop and the collection approaches.
In summary, for an unsorted array the most efficient way to test containment is a straightforward loop; if the data can be sorted, a binary search or a HashSet gives O(log n) or O(1) performance respectively.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
