In this short article, you'll learn how to check if an array contains a certain value in Java. We will look at different examples of string as well as primitive arrays to find out if a certain value exists.
String Arrays
The simplest and easiest way to check if a string array contains a certain value is the following:
- Convert the array into a list
- Use the
List.contains()
method to check if the value exists in the list
Here is an example:
String[] names = {"Atta", "John", "Emma", "Tom"};
// convert array to list
List<String> list = Arrays.asList(names);
// check if `Emma` exists in list
if(list.contains("Emma")) {
System.out.println("Hi, Emma 👋");
}
You should see the following output:
Hi, Emma 👋
Java 8 Stream API
In Java 8 or higher, you can also use the Stream API to check if a value exists in an array as shown below:
String[] names = {"Atta", "John", "Emma", "Tom"};
// check if `Atta` exists in list
boolean exist = Arrays.stream(names).anyMatch("Atta"::equals);
if(exist) {
System.out.println("Hi, Atta 🙌");
}
The above code will output the following:
Hi, Atta 🙌
Check Multiple Values
The following example demonstrates how to check if a string array contains multiple values in Java:
String[] names = {"Atta", "John", "Emma", "Tom"};
// convert array to list
List<String> list = Arrays.asList(names);
// check 'Atta' & `John`
if (list.containsAll(Arrays.asList("Atta", "John"))) {
System.out.println("Hi, Atta & John 🎉");
}
You should see the following output:
Hi, Atta & John 🎉
Primitive Arrays
For primitive arrays like int[]
, you have to loop all elements to test the condition manually:
int[] years = {2015, 2016, 2017, 2018, 2019, 2020};
// loop all elements
for (int y : years) {
if (y == 2019) {
System.out.println("Goodbye, 2019!");
break;
}
}
Here is how the output looks like:
Goodbye, 2019!
Java 8 IntStream
& LongStream
With Java 8 or higher, you can convert the primitive array to a Stream and then check if it contains a certain value as shown below:
// Integer Array
int[] years = {2015, 2016, 2017, 2018, 2019, 2020};
// check if `2020` exits
boolean yearExist = IntStream.of(years).anyMatch(x -> x == 2019);
if(yearExist) {
System.out.println("Welcome 2020 🌟");
}
// Long Array
long[] prices = {12, 15, 95, 458, 54, 235};
// check if `54` exits
boolean priceExist = LongStream.of(prices).anyMatch(x -> x == 54);
if(priceExist) {
System.out.println("Yup, 54 is there 💰");
}
The above code snippet outputs the following:
Welcome 2020 🌟
Yup, 54 is there 💰
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.