Table of Contents
2. Binary Search (for sorted arrays)
3. Using ArrayList or Collections (alternative approach)
4. Using Streams (Java 8)
Home Java javaTutorial How do you search for an element in an array in Java?

How do you search for an element in an array in Java?

Sep 02, 2025 am 02:03 AM
java array

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.

How do you search for an element in an array in Java?

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() returns true or false .
  • list.indexOf(30) returns the index or -1 if not found.
  • Note: Works with wrapper types ( Integer[] ), not primitive arrays like int[] .

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() returns true 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 use contains .
  • 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to find an element in an array in PHP? How to find an element in an array in PHP? Sep 07, 2025 am 06:45 AM

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.

Wi-Fi calling not working Wi-Fi calling not working Sep 05, 2025 am 04:44 AM

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

How to convert an object to an array in PHP? How to convert an object to an array in PHP? Sep 14, 2025 am 03:14 AM

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.

Notepad   how to change case (uppercase/lowercase) Notepad how to change case (uppercase/lowercase) Sep 03, 2025 am 09:22 AM

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

How to check if an array is associative or sequential in PHP? How to check if an array is associative or sequential in PHP? Sep 16, 2025 am 05:40 AM

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

How to get the file extension from a String in Java? How to get the file extension from a String in Java? Sep 16, 2025 am 03:40 AM

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

How to implement the Comparable interface in Java? How to implement the Comparable interface in Java? Sep 16, 2025 am 03:44 AM

ToimplementComparableinJava,definethecompareTomethodfornaturalordering.1.ImplementComparableinterface.2.OverridecompareTotoreturnnegative,zero,orpositivevaluesbasedoncomparison.3.UseCollections.sort()orArrays.sort()tosortobjects.4.Formultiplefields,c

Compressed (zipped) folders error: Access Denied [Fixed] Compressed (zipped) folders error: Access Denied [Fixed] Sep 06, 2025 am 06:16 AM

Ifyougetan"AccessDenied"errorwhenopeningazippedfolder,trythesesteps:1.RunFileExplorerasAdministrator.2.Takeownershipofthefolder.3.Modifypermissionstoallowfullcontrol.4.Copythefiletoauser-accessiblelocation.5.UseCommandPrompttoextract(tar-xf

See all articles