Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

When we write unit tests in Java, especially with the JUnit framework, it’s common to verify that a Collection contains a specific element. As a powerful library, Hamcrest offers a simple and expressive way to perform these checks using Matchers.

In this quick tutorial, we’ll explore how to check whether a Collection contains a specific element using Hamcrest’s Matchers. Further, as arrays are commonly used data containers, we’ll also discuss how to perform the same check on arrays.

2. Setting up Hamcrest

Before diving into examples, we need to ensure that Hamcrest is included in our project. If we’re using Maven, we can add the following dependency to our pom.xml:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

We can check Maven Central for the latest version of Hamcrest.

So, let’s prepare a List and an array as inputs:

static final List<String> LIST = List.of("a", "b", "c", "d", "e", "f");
static final String[] ARRAY = { "a", "b", "c", "d", "e", "f" };

Next, let’s check whether they contain or don’t contain a specific element.

3. Using Hamcrest Matchers and assertThat()

Hamcrest provides a rich set of Matchers to work with Collections. To check if a Collection contains a specific element, we can use the hasItem() Matcher from the org.hamcrest.Matchers class. Let’s walk through some examples to see how this works in practice.

First, let’s import static the hasItem() method to make the code easy to read:

import static org.hamcrest.Matchers.hasItem;

Then, we can use it to verify if a Collection contains or doesn’t contain an element:

assertThat(LIST, hasItem("a"));
assertThat(LIST, not(hasItem("x")));

In the above code, we used the not() method to negate the match parameter’s logic.

The hasItem() method is straightforward in verifying if a Collection contains an element. However, we cannot use it to check arrays.

To check if an array contains a specific element, we can use the hasItemInArray() method, also from the org.hamcrest.Matchers class:

assertThat(ARRAY, hasItemInArray("a"));
assertThat(ARRAY, not(hasItemInArray("x")));

As the examples show, we can easily solve our problem by employing Harmcrest’s convenient hasItem() and hasItemInArray().

4. Using JUnit’s assertTrue() and assertFalse()

We’ve seen Harmcrest’s Matchers, which are easy to use. Alternatively, we can use JUnit’s assertTrue() and assertFalse() methods to achieve the goal:

assertTrue(LIST.contains("a"));
assertFalse(LIST.contains("x"));

This time, we use Collection‘s contains() method to check if the target element exists in the Collection.

However, if the input is an array, unlike Collection.contains(), there is no simple one-shot method to check. Fortunately, we have multiple ways to check if an array contains a value in Java.

Next, let’s see how to use these methods with JUnit assertTrue() and assertFalse():

assertTrue(Arrays.stream(ARRAY).anyMatch("a"::equals));
assertFalse(Arrays.asList(ARRAY).contains("z"));

As the code shows, we can convert the array to a List or use Stream API to examine whether a specific value exists in the array.

From the above examples, we can also see that if we want to check whether a Collection contains an element or not, both Hamcrest Matchers and JUnit assertions with Collection.contains() approaches are straightforward. However, when we need to perform the same check on an array, Hamcrest Matchers can be a better choice, as they’re more compact and easier to understand.

5. Conclusion

In this quick article, we’ve explored various ways to assert if a Collection or array contains a specific element using JUnit and Hamcrest.

Using Hamcrest’s hasItem() or hasItemInArray(), we can easily verify the presence of a specific element within Collections or arrays in our unit tests. Further, the Matcher makes our tests more readable and expressive, enhancing the clarity and maintainability of our test code.

Alternatively, we can use methods provided by Java standard API to examine if the Collection and the array contain the target element, and then use JUnit’s standard assertTrue() and assertFalse() assertions to do the job.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW