Sentry Answers>Java>

Find a specific value in an array in Java

Find a specific value in an array in Java

David Y.

The ProblemJump To Solution

Using Java, how can I test whether an array contains a specific value?

The Solution

We can achieve this for an array of any type using Java’s Stream API, introduced in Java 8. Streams are a method for processing collections of objects and can be used to perform operations such as finding values in arrays without having to explicitly loop through them. In a single line of code, we can give a stream a function to execute at every element in a given collection and retrieve the result. For example, to find a string in an array of strings, we could use the following code:

Click to Copy
import java.util.Arrays; public class Main { public static void main(String[] args) { String[] products = new String[]{"Coffee", "Tea", "Chocolate Bar"}; if (Arrays.stream(products).anyMatch("Coffee"::equals)) { System.out.println("Array contains 'Coffee'!"); } else { System.out.println("Array does not contain 'Coffee'."); } } }

Different stream types are required for arrays of different types. To find an integer in an array of integers, we could use an IntStream. For example:

Click to Copy
import java.util.stream.IntStream; public class Main { public static void main(String[] args) { int[] values = {1, 2, 3, 4, 5}; if (IntStream.of(values).anyMatch(x -> x == 3)) { System.out.println("Array contains 3!"); } else { System.out.println("Array does not contain 3."); } } }

We can adapt this for longs or doubles by using a LongStream or DoubleStream instead.

An alternative but less generalizable method for achieving this is to cast our array to a list using Arrays.asList and then use the contains method on that list. While this may be more readable for a developer unfamiliar with Java’s Stream API, it does not work for primitive values like for arrays with ints, doubles, or longs. However, it will work for an array of strings:

Click to Copy
import java.util.Arrays; public class Main { public static void main(String[] args) { String[] products = new String[]{"Coffee", "Tea", "Chocolate Bar"}; if (Arrays.asList(products).contains("Coffee")) { System.out.println("Array contains 'Coffee'!"); } else { System.out.println("Array does not contain 'Coffee'."); } } }

Note that if we attempt this same approach with an array of primitive types, the contains method will not throw an error, but will always return false, even if the array contains the value we specify. We can run the code below to verify this:

Click to Copy
// BROKEN CODE DO NOT USE import java.util.Arrays; public class Main { public static void main(String[] args) { int[] values = {1, 2, 3, 4, 5}; if (Arrays.asList(values).contains(3)) { System.out.println("Array contains 3!"); } else { // this block will be executed System.out.println("Array does not contain 3."); } } } // BROKEN CODE DO NOT USE
  • Sentry BlogException Handling in Java (with Real Examples)
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Loved by over 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.