How do you search for an element in an array in Java?
The best way to search for array elements in Java depends on whether the array is sorted and its performance requirements: for small unsorted arrays, use linear search (time complexity O(n)); for sorted arrays, use Arrays.binarySearch() (time complexity O(log n)); if you use object arrays and pursue simplicity, you can convert to List and call contains() or indexOf(); when you prefer functional style in Java 8, you can use Arrays.stream().anyMatch() to implement a simple line of code, but the performance is slightly lower than that of traditional loops, so choosing methods requires weighing performance, readability and whether the data is sorted.
In Java, searching for an element in an array depends on whether the array is sorted or not, and what kind of performance or simplicity you're aiming for. Here are the most common and practical ways:
1. Linear Search (for unsorted arrays)
If the array isn't sorted, the simplest approach is to loop through each element until you find a match.
int[] arr = {10, 20, 30, 40, 50}; int target = 30; boolean found = false; for (int i = 0; i < arr.length; i ) { if (arr[i] == target) { System.out.println("Element found at index " i); found = true; break; } } if (!found) { System.out.println("Element not found"); }
- Works with any array, sorted or not.
- Time complexity: O(n).
- Best when the array is small or unsorted.
2. Binary Search (for sorted arrays)
If the array is sorted, you can use binary search for better performance.
You can use the built-in method from Arrays.binarySearch()
:
import java.util.Arrays; int[] arr = {10, 20, 30, 40, 50}; int target = 30; int index = Arrays.binarySearch(arr, target); if (index >= 0) { System.out.println("Element found at index " index); } else { System.out.println("Element not found"); }
- Only works on sorted arrays.
- Time complexity: O(log n).
- If the array isn't sorted, sort it first using
Arrays.sort(arr)
— but that adds O(n log n) overhead.
⚠️ Important: If you use
binarySearch
on an unsorted array, the result is undefined.
3. Using ArrayList or Collections (alternative approach)
If you're open to using collections instead of raw arrays, you can convert the array to a List
and use contains()
or indexOf()
:
import java.util.Arrays; import java.util.List; Integer[] arr = {10, 20, 30, 40, 50}; List<Integer> list = Arrays.asList(arr); if (list.contains(30)) { System.out.println("Element found"); }
-
contains()
returnstrue
orfalse
. -
list.indexOf(30)
returns the index or -1 if not found. - Note: Works with wrapper types (
Integer[]
), not primitive arrays likeint[]
.
4. Using Streams (Java 8)
Modern Java allows using streams for more readable one-liners:
import java.util.Arrays; int[] arr = {10, 20, 30, 40, 50}; boolean found = Arrays.stream(arr).anyMatch(x -> x == 30); if (found) { System.out.println("Element found"); }
-
anyMatch()
returnstrue
if any element matches. - You can also use
IntStream
for more operations. - Slightly more overhead than a simple loop, but clean and functional in style.
So, the best method depends on your situation:
- Unsorted array, small size : Use linear search (simple loop).
- Sorted array : Use
Arrays.binarySearch()
. - Want clean syntax and using objects : Convert to
List
and usecontains
. - Using Java 8 and prefer functional style : Use
Arrays.stream()
.
Basically, it's about trade-offs between performance, readability, and whether the data is sorted.
The above is the detailed content of How do you search for an element in an array in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



To find the array element, select the function according to the requirements: in_array() check whether the value exists, array_search() gets the key corresponding to the value, and array_key_exists() checks whether the key exists.

EnsureyourdeviceandcarriersupportWi-Ficallingandenableitinsettings—iPhone:Settings>Phone>Wi-FiCalling;Android:Settings>Network&Internet>Mobilenetwork>Advanced>Wi-FiCalling;confirmcarriercompatibilityandcompleteemergencyaddressre

Use (array) to convert simple objects into arrays. If they contain private or protected properties, the key names will have special characters; for nested objects, recursive functions should be used to traverse the conversion to ensure that all hierarchical objects become associative arrays.

TochangetextcaseinNotepad ,firstselectthetext,thengotoEdit>ConvertCaseToandchoosethedesiredoption:1.UPPERCASE–convertsalltexttouppercase.2.lowercase–convertsalltexttolowercase.3.TitleCase–capitalizesthefirstletterofeachword.4.Sentencecase–capital

Anarrayissequentialifitskeysmatchacontinuousintegersequencestartingfrom0,determinedbycomparingarray_keys($array)witharray_keys(array_keys($array));otherwise,itisassociative.

TogetafileextensioninJava,uselastIndexOf()tofindthelastdotandextractthesubstringafterit,ensuringthedotisn'tatindex0orabsent;forcleanercode,useApacheCommonsIO’sFilenameUtils.getExtension(),whichhandlesedgecaseslikehiddenfilesandpathswithmultipledots.

ToimplementComparableinJava,definethecompareTomethodfornaturalordering.1.ImplementComparableinterface.2.OverridecompareTotoreturnnegative,zero,orpositivevaluesbasedoncomparison.3.UseCollections.sort()orArrays.sort()tosortobjects.4.Formultiplefields,c
![Compressed (zipped) folders error: Access Denied [Fixed]](https://img.php.cn/upload/article/001/431/639/175711056270360.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Ifyougetan"AccessDenied"errorwhenopeningazippedfolder,trythesesteps:1.RunFileExplorerasAdministrator.2.Takeownershipofthefolder.3.Modifypermissionstoallowfullcontrol.4.Copythefiletoauser-accessiblelocation.5.UseCommandPrompttoextract(tar-xf
