Java 8 Check if Array Contains a Certain Value Example
1. Introduction
An array is a data structure which holds a fixed number of values of a single type. In this example, I will demonstrate how to check if an array contains a certain value in three ways:
- Convert an array to a
Collection
and check with thecontains
method - Use
Arrays.binarySearch
to check when the array is sorted - Convert an array to Java 8
Stream
and check withanyMatch
,filter
, orfindAny
methods
2. Technologies used
The example code in this article was built and run using:
- Java 1.8.101
- Maven 3.3.9
- Eclipse Oxygen
- JUnit 4.12
3. Maven Project
3.1 Dependency
Add JUnit to the pom.xml.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>zheng.jcg.demo</groupId> <artifactId>java8-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
3.2 Sample Data
I will create a SampleData
class which has the equals
method. This class will be used to form an object array.
SampleData.java
package com.zheng.demo; public class SampleData { private int key; private String name; public SampleData(int key, String name) { super(); this.key = key; this.name = name; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SampleData other = (SampleData) obj; if (key != other.key) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + key; return result; } @Override public String toString() { return "SampleData [key=" + key + ", name=" + name + "]"; } }
3.3 Check Item from Array with Stream
JDK 8 Stream interface provides three methods that we can use to check an item from an array.
Return type | Method | Description | |
---|---|---|---|
Optional<T> | findAny() | Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. | |
Stream<T> | filter(Predicate<? super T> predicate) | Returns a stream consisting of the elements of this stream that match the given predicate. | |
boolean | anyMatch(Predicate<? super T> predicate) | Returns whether any elements of this stream match the provided predicate. |
In this step, I will create a CheckItemFromArray_Java8
class to demonstrate how to check an item in an array.
CheckItemFromArray_Java8.java
package com.zheng.demo; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; public class CheckItemFromArray_Java8 { public boolean byDoubleStreamAnyMatch(double[] values, double targetValue) { return DoubleStream.of(values).anyMatch(x -> x == targetValue); } public boolean byDoubleStreamAnyMatch_2(double[] values, double targetValue) { return DoubleStream.of(values).anyMatch(x -> Double.compare(x, targetValue) == 0); } public boolean byIntStreamAnyMatch(int[] values, int targetValue) { return IntStream.of(values).anyMatch(x -> x == targetValue); } public boolean byLongStreamAnyMatch(long[] values, long targetValue) { return LongStream.of(values).anyMatch(x -> x == targetValue); } public <T> boolean byStreamAnyMatch(T[] array, T targetValue) { return Arrays.stream(array).anyMatch(targetValue::equals); } public boolean byStreamAnyMatchEquals(String[] checkingArray, String targetValue) { return Arrays.stream(checkingArray).anyMatch(targetValue::equals); } public boolean byStreamAnyMatchEqualsIgnoreCase(String[] checkingArray, String targetValue) { return Arrays.stream(checkingArray).anyMatch(targetValue::equalsIgnoreCase); } public boolean byStreamFilter(String[] checkingArray, String targetValue) { List<String> filterData = Arrays.stream(checkingArray).filter(x -> targetValue.equals(x)) .collect(Collectors.toList()); return !filterData.isEmpty(); } public boolean byStreamFindAny(int[] values, int targetValue) { int found = Arrays.stream(values).filter(x -> targetValue == x).findAny().orElse(-1); return found != -1; } public boolean byStreamFindAny(String[] checkingArray, String targetValue) { String found = Arrays.stream(checkingArray).filter(x -> targetValue.equals(x)).findAny().orElse(null); return found != null; } }
Note: the equality check is different based on the object type.
4. JUnit Tests
4.1 Test Data Provider
I will create a TestDataProvider
class for the common data.
TestDataProvider.java
package com.zheng.demo; public class TestDataProvider { public static double[] DOUBLE_ARRAY = new double[] { 1d, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; public static int[] INT_ARRAY = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; public static long[] LONG_ARRAY = new long[] { 1l, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; public static final int NOT_IN_INT_ARRAY = 20; public static String[] STRING_ARRAY = new String[] { "AA", "BB", "CC", "DD", "EE" }; public static final String STRING_NOT_IN_ARRAY = "D"; public static SampleData[] getSampleDataArray() { SampleData[] objects = new SampleData[4]; objects[0] = new SampleData(1, "Mary"); objects[1] = new SampleData(2, "Terry"); objects[2] = new SampleData(3, "Tom"); objects[3] = new SampleData(4, "John"); return objects; } }
4.2 Check Item from Array with Arrays
java.util.Arrays class provides binarySearch
which finds the specified element using the binary search algorithm.
I will create an ArraysBinarySearchTest
class to search an item.
ArraysBinarySearchTest.java
package com.zheng.demo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collections; import org.junit.Test; public class ArraysBinarySearchTest { @Test public void findfrom_sorted_double_Array() { for (double item : TestDataProvider.DOUBLE_ARRAY) { int foundIndex = Arrays.binarySearch(TestDataProvider.DOUBLE_ARRAY, item); assertTrue(foundIndex >= 0); } } @Test public void findfrom_sorted_int_Array() { for (int item : TestDataProvider.INT_ARRAY) { int foundIndex = Arrays.binarySearch(TestDataProvider.INT_ARRAY, item); assertTrue(foundIndex >= 0); } } @Test public void findfrom_sorted_long_Array() { for (long item : TestDataProvider.LONG_ARRAY) { int foundIndex = Arrays.binarySearch(TestDataProvider.LONG_ARRAY, item); assertTrue(foundIndex >= 0); } } @Test public void findfrom_sorted_String_Array() { String[] stringArray = TestDataProvider.STRING_ARRAY; Collections.sort(Arrays.asList(stringArray)); int foundIndex = Arrays.binarySearch(stringArray, TestDataProvider.STRING_NOT_IN_ARRAY); assertFalse(foundIndex >= 0); for (String item : stringArray) { foundIndex = Arrays.binarySearch(stringArray, item); assertTrue(foundIndex >= 0); } } }
4.3 Check Item from Array with Collection
java.util.Collection interface provides contains(Object o)
which returns true if this collection contains the specified element.
I will create a CollectionContainsTest
class to convert an array into a List
or Set
and use thecontains
method to check if an array contains a certain value.
CollectionContainsTest.java
package com.zheng.demo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Before; import org.junit.Test; public class CollectionContainsTest { private String[] stringArray; @Before public void setup() { stringArray = TestDataProvider.STRING_ARRAY; } @Test public void check_byListContains() { boolean found = Arrays.asList(stringArray).contains(TestDataProvider.STRING_NOT_IN_ARRAY); assertFalse(found); for (String item : stringArray) { found = Arrays.asList(stringArray).contains(item); assertTrue(found); } } @Test public void check_bySetContains() { Set set = new HashSet(Arrays.asList(stringArray)); boolean found = set.contains(TestDataProvider.STRING_NOT_IN_ARRAY); assertFalse(found); for (String item : stringArray) { found = set.contains(item); assertTrue(found); } } }
4.4 Test for CheckItemFromArray_Java8
In this step, I will create CheckItemFromArray_Java8Test
to test the methods defined in CheckItemFromArray_Java8.
CheckItemFromArray_Java8Test.java
package com.zheng.demo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import org.junit.Before; import org.junit.Test; public class CheckItemFromArray_Java8Test { private CheckItemFromArray_Java8 testObject = new CheckItemFromArray_Java8(); private int[] intValues; private long[] longValues; private double[] doubleValues; private String[] checkingArray; @Before public void setup() { checkingArray = TestDataProvider.STRING_ARRAY; intValues = TestDataProvider.INT_ARRAY; longValues = TestDataProvider.LONG_ARRAY; doubleValues = TestDataProvider.DOUBLE_ARRAY; } @Test public void byStreamAnyMatchEqualsIgnoreCase() { boolean found = testObject.byStreamAnyMatchEqualsIgnoreCase(checkingArray, TestDataProvider.STRING_NOT_IN_ARRAY); assertFalse(found); Arrays.stream(checkingArray) .forEach(x -> assertTrue(testObject.byStreamAnyMatchEqualsIgnoreCase(checkingArray, x))); } @Test public void byStreamAnyMatchEquals() { boolean found = testObject.byStreamAnyMatchEquals(checkingArray, TestDataProvider.STRING_NOT_IN_ARRAY); assertFalse(found); Arrays.stream(checkingArray).forEach(x -> assertTrue(testObject.byStreamAnyMatchEquals(checkingArray, x))); } @Test public void byStreamFilter() { boolean found = testObject.byStreamFilter(checkingArray, TestDataProvider.STRING_NOT_IN_ARRAY); assertFalse(found); Arrays.stream(checkingArray).forEach(x -> assertTrue(testObject.byStreamFilter(checkingArray, x))); } @Test public void byStreamFindAny() { boolean found = testObject.byStreamFindAny(checkingArray, TestDataProvider.STRING_NOT_IN_ARRAY); assertFalse(found); Arrays.stream(checkingArray).forEach(x -> assertTrue(testObject.byStreamFindAny(checkingArray, x))); } @Test public void test_byAnyMatch() { SampleData[] objects = TestDataProvider.getSampleDataArray(); boolean found = testObject.byStreamAnyMatch(objects, new SampleData(1, "Mary")); assertTrue(found); found = testObject.byStreamAnyMatch(objects, new SampleData(6, "Mary")); assertFalse(found); } @Test public void checkInt_byStreamAnyMatch() { IntStream.of(intValues).forEach(x -> assertTrue(testObject.byIntStreamAnyMatch(intValues, x))); boolean found = testObject.byIntStreamAnyMatch(intValues, TestDataProvider.NOT_IN_INT_ARRAY); assertFalse(found); } @Test public void checkLong_byStreamAnyMatch() { boolean found = testObject.byLongStreamAnyMatch(longValues, TestDataProvider.NOT_IN_INT_ARRAY); assertFalse(found); LongStream.of(longValues).forEach(x -> assertTrue(testObject.byLongStreamAnyMatch(longValues, x))); } @Test public void checkDouble_byStreamAnyMatch() { boolean found = testObject.byDoubleStreamAnyMatch(doubleValues, TestDataProvider.NOT_IN_INT_ARRAY); assertFalse(found); DoubleStream.of(doubleValues).forEach(x -> assertTrue(testObject.byDoubleStreamAnyMatch(doubleValues, x))); } @Test public void checkDouble_byStreamAnyMatch_2() { boolean found = testObject.byDoubleStreamAnyMatch_2(doubleValues, TestDataProvider.NOT_IN_INT_ARRAY); assertFalse(found); DoubleStream.of(doubleValues).forEach(x -> assertTrue(testObject.byDoubleStreamAnyMatch(doubleValues, x))); } @Test public void byStreamFindAny_withInt() { boolean found = testObject.byStreamFindAny(intValues, TestDataProvider.NOT_IN_INT_ARRAY); assertFalse(found); IntStream.of(intValues).forEach(x -> assertTrue(testObject.byStreamFindAny(intValues, x))); } }
5. Demo
Execute mvn clean install
and capture the output:
Tests Output
C:\gitworkspace\java8-demo>mvn clean install [INFO] Scanning for projects... [INFO] [INFO] ---------------------< zheng.jcg.demo:java8-demo >---------------------- [INFO] Building java8-demo 0.0.1-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ java8-demo --- [INFO] Deleting C:\gitworkspace\java8-demo\target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java8-demo --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ java8-demo --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 2 source files to C:\gitworkspace\java8-demo\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java8-demo --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ java8-demo --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! [INFO] Compiling 4 source files to C:\gitworkspace\java8-demo\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java8-demo --- [INFO] Surefire report directory: C:\gitworkspace\java8-demo\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.zheng.demo.ArraysBinarySearchTest Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.058 sec Running com.zheng.demo.CheckItemFromArray_Java8Test Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.051 sec Running com.zheng.demo.CollectionContainsTest Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec Results : Tests run: 16, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ java8-demo --- [INFO] Building jar: C:\gitworkspace\java8-demo\target\java8-demo-0.0.1-SNAPSHOT.jar [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ java8-demo --- [INFO] Installing C:\gitworkspace\java8-demo\target\java8-demo-0.0.1-SNAPSHOT.jar to C:\repo\zheng\jcg\demojava8-demo\0.0.1-SNAPSHOT\java8-demo-0.0.1-SNAPSHOT.jar [INFO] Installing C:\gitworkspace\java8-demo\pom.xml to C:\repo\zheng\jcg\demo\java8-demo\0.0.1-SNAPSHOT\java8-demo-0.0.1-SNAPSHOT.pom [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 5.727 s [INFO] Finished at: 2018-11-08T09:50:35-06:00 [INFO] ------------------------------------------------------------------------ C:\gitworkspace\java8-demo>
6. Summary
In this example, we demonstrated how to check if an array contains a certain value using Java 8 Stream
interface as well as the Collection’s contains
method.
7. Download the Source Code
This example consists of a Maven project to check if an array contains a certain value.
You can download the full source code of this example here: Java 8 Check if Array Contains a Certain Value Example