David Y.
—Using Java, how can I test whether an array contains a specific value?
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:
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:
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:
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:
// 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
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.