Java Array Contains Example
1. Introduction
An array is a container object that holds a fixed number of elements with a single type. Java not only provides Arrays to copy, sort, and search elements, it also provides the collection framework to check if a certain value in a collection with the contains method.
In this example, I will demonstrate:
- Find an element in a sorted array via
Arrays.binarySearch
. - Find an element in an array via
Stream.anyMatch
method. - Find an element in an array via
AbstractCollection
.contains
method. - Find an element via a loop.
2. Technologies Used
The example code in this article was built and run using:
- Java 11
- Maven 3.3.9
- Eclipse Oxygen
- Junit 4.12
3. Maven Project
3.1 Dependencies
I will include Junit
in 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>jcg-zheng-demo</groupId> <artifactId>array-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> <configuration> <release>11</release> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
3.2 POJO
I will create a POJO
class which has name
and age
members and can be sorted based on its age
. It has three methods:
equals
– generated by Eclipse IDE based on bothname
andage
members.hashCode
– generated by Eclipse IDE based on bothname
andage
members.compareTo
– compare to otherPOJO
object based on theage
member.
POJO.java
package jcg.zheng.demo.model; public class POJO implements Comparable<POJO> { private int age; private String name; public POJO() { super(); } public POJO(String name, int age) { super(); this.name = name; this.age = age; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; POJO other = (POJO) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public String toString() { return "POJO [name=" + name + ", age=" + age + "]"; } @Override public int compareTo(POJO o) { if (this.age == (o.age)) return 0; else if ((this.age) > (o.age)) return 1; else return -1; } }
3.3 FindService
I will create a FindService
class which finds an element from an array via a loop. This is the most common way prior to Java 8.
It has three methods:
containsInt
– find an element from an integer array.containsObject
– find an element from an object array.containsString
– find an element from a string array.
FindService.java
package jcg.zheng.demo.api; import jcg.zheng.demo.model.POJO; public class FindService { public boolean containsInt(int[] numbers, int searchingItem) { boolean found = false; for (int element : numbers) { if (element == searchingItem) { found = true; break; } } return found; } public boolean containsObject(POJO[] objects, POJO searchingItem) { boolean found = false; for (POJO element : objects) { if (element.equals(searchingItem)) { found = true; break; } } return found; } public boolean containsString(String[] strings, String searchingItem) { boolean found = false; for (String element : strings) { if (element.equalsIgnoreCase(searchingItem)) { found = true; break; } } return found; } }
4. JUnit Test
4.1 Find Integer Test
I will create a FindIntTest
class which includes three tests to find an element from a sorted integer array:
findvia_binarySearch
– usesArrays.binarySearch
to find an element.findvia_stream
– usesIntStream.anyMatch
to find an element.findvia_loop
– usesFindService.containsInt
to find an element.
FindIntTest.java
package jcg.zheng.demo.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.stream.IntStream; import org.junit.Test; import jcg.zheng.demo.api.FindService; public class FindIntTest { int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; @Test public void findvia_binarySearch() { int foundOne = Arrays.binarySearch(digits, 1); assertEquals(1, foundOne); int foundTwo = Arrays.binarySearch(digits, 2); assertEquals(2, foundTwo); int foundNone = Arrays.binarySearch(digits, 11); assertEquals(-11, foundNone); } @Test public void findvia_list_isbad() { boolean shouldContain = Arrays.asList(digits).contains(1); assertFalse(shouldContain); } @Test public void findvia_loop() { FindService foundService = new FindService(); assertTrue(foundService.containsInt(digits, 1)); assertFalse(foundService.containsInt(digits, 100)); } @Test public void findvia_stream() { assertTrue(IntStream.of(digits).anyMatch(x -> x == 1)); assertFalse(IntStream.of(digits).anyMatch(x -> x == 10)); } }
Please note that the List.containts
method should not be used for the primitive data type as the findvia_list_isbad
shows.
Execute mvn test -Dtest=FindIntTest and capture the output here:
Junit Output
Running jcg.zheng.demo.api.FindIntTest Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.132 sec Results : Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
4.2 Find String Test
I will create a FindStriingTest
class which contains four tests to find an element from a sorted string array:
findvia_binarySearch
– usesArrays.binarySearch
to find an element.findvia_stream
– usesStream.anyMatch
to find an element.findvia_loop
– usesFindService.containsString
to find an element.findvia_list
– usesList.contains
to find an element.
FindStringTest.java
package jcg.zheng.demo.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.junit.Test; import jcg.zheng.demo.api.FindService; public class FindStringTest { String[] alphabet = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; @Test public void findvia_binarySearch() { int foundA = Arrays.binarySearch(alphabet, "A"); assertEquals(0, foundA); int foundB = Arrays.binarySearch(alphabet, "B"); assertEquals(1, foundB); int foundNone = Arrays.binarySearch(alphabet, "1"); assertEquals(-1, foundNone); } @Test public void findvia_list() { assertTrue(Arrays.asList(alphabet).contains("A")); assertFalse(Arrays.asList(alphabet).contains("1")); } @Test public void findvia_loop() { FindService foundService = new FindService(); assertTrue(foundService.containsString(alphabet, "A")); assertFalse(foundService.containsString(alphabet, "1")); } @Test public void findvia_stream() { assertTrue(Arrays.stream(alphabet).anyMatch("A"::equals)); assertFalse(Arrays.stream(alphabet).anyMatch("1"::equals)); } }
Execute mvn test -Dtest=FindStringTest and capture output here”
Junit Output
Running jcg.zheng.demo.api.FindStringTest Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.155 sec Results : Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
4.3 Find Object Test
I will create a FindObjectTest
class which has four tests to find an element from a sorted object array:
findvia_binarySearch
– usesArrays.binarySearch
to find an element.findvia_stream
– usesStream.anyMatch
to find an element.findvia_loop
– usesFindService.containsObject
to find an element.findvia_list
– usesList.contains
to find an element.
Please note that the object class must have equals
and hashCode
methods.
FindObjectTest
package jcg.zheng.demo.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import jcg.zheng.demo.api.FindService; import jcg.zheng.demo.model.POJO; public class FindObjectTest { POJO badMark = new POJO("Mark_NA", 60); POJO mark = new POJO("Mark", 10); POJO[] objects = new POJO[5]; @Test public void findvia_binarySearch() { int foundOne = Arrays.binarySearch(objects, mark); assertEquals(0, foundOne); int foundTwo = Arrays.binarySearch(objects, badMark); assertEquals(-6, foundTwo); } @Test public void findvia_list() { assertTrue(Arrays.asList(objects).contains(mark)); assertFalse(Arrays.asList(objects).contains(badMark)); } @Test public void findvia_loop() { FindService foundService = new FindService(); assertTrue(foundService.containsObject(objects, mark)); assertFalse(foundService.containsObject(objects, badMark)); } @Test public void findvia_stream() { assertTrue(Arrays.stream(objects).anyMatch(mark::equals)); assertFalse(Arrays.stream(objects).anyMatch(badMark::equals)); } @Before public void setup() { objects[0] = mark; objects[1] = new POJO("Mary", 20); objects[2] = new POJO("Terry", 30); objects[3] = new POJO("Tom", 40); objects[4] = new POJO("John", 50); } }
Execute mvn test -Dtest=FindObjectTest and capture output here:
Junit Output
Running jcg.zheng.demo.api.FindObjectTest Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.26 sec Results : Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
5. Summary
In the example, I demonstrated four ways to find an element in an array:
- Utilize Java
AbstractCollection.contains
. Note: does not work for the primitive data type. - Utilize Java
Arrays.binarySearch
. Note: only works for a sorted array - Utilize Java
Stream.anyMatch
. Note: works for Java 8 and higher version. - Utilize a loop to find the element.
Please note when finding an element in an object array, the object class must have an equal
method.
6. Download the Source Code
You can download the full source code of this example here: Java Array Contains Example