Explain Codes LogoExplain Codes Logo

How do I determine whether an array contains a particular value in Java?

java
arrays
streams
performance
Nikita BarsukovbyNikita Barsukov·Aug 13, 2024
TLDR

Need an efficient approach? Use Java Streams for a quick existence check:

// I'm a little stream, short and stout boolean found = Arrays.stream(array).anyMatch(val::equals);

Substitute array with your array and val with the target value. If val is in the array, it returns true.

Optimizing based on data types

Different data types, different strategies. Let's delve into optimal approaches for different kinds of data.

Primitives: The basics

IntStream and Arrays.stream are your friends when handling primitive arrays:

// is '42' the answer to the Universe? boolean isFound = IntStream.of(intArray).anyMatch(x -> x == 42);

Object arrays: Null checks and equals method

When handling Object arrays, include null value checks with the equals method:

// Sherlock Holmes mode: finding null corpses and values for (String s : array) { if (s != null && s.equals(value)) { return true; } }

Large arrays: Set for speed

For large arrays, converting the array to a Set drastically improves performance:

// Never underestimate the power of fashion sets Set<String> stylishSet = new HashSet<>(Arrays.asList(array)); boolean exists = stylishSet.contains(value);

Pointer: Keep your static arrays private final and use Collections.unmodifiableSet to create immutable sets.

Sorted Arrays: Binary search to the rescue

Use binary search in sorted arrays to find an element fastest:

// Binary search: For when you're sorted and efficient boolean exists = Arrays.binarySearch(sortedArray, value) >= 0;

Remember: Binary Search works only with sorted arrays.

Libraries: Easy as pie

Prefer simpler solutions? Use Apache Commons Lang:

// This isn't an Array, it's a VIP lang boolean contains = ArrayUtils.contains(array, value);

Just import the library to enjoy simplicity and convenience.

Dealing with auto-boxing and Streams

Streams have been designed meticulously to handle primitives without auto-boxing. This prevents distortions when handling primitive types.

Stream operations: The gesture of generosity

Streams open doors for functional-style operations for complex checks:

// For when you need a deeper touch of functional flavor boolean found = Arrays.stream(array) .filter(Objects::nonNull) .anyMatch(val::equals);

Choosing the right tool

Decision-making is key. Depending on the array size, type of data, and whether the array is sorted, different methods fare better:

  • <u>Small Array:</u> Simple loop or contains method.
  • <u>Primitive Array:</u> IntStream or Arrays.stream.
  • <u>Object Array:</u> Null checks with equals.
  • <u>Large Array:</u> Convert to Set for faster membership checks.
  • <u>Sorted Array:</u> Use binarySearch.