Hamcrest Collections Cookbook

1. Introduction

This cookbook illustrates how to make use of Hamcrest matchers to work with and test collections.

The format of the cookbook is example focused and practical – no extraneous details and explanations necessary.

First, let’s do a quick static import to cover most of the utility APIs we’re going to use next:

import static org.hamcrest.Matchers.*;

2. The Cookbook

Check if single element is in a collection

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItem("cd"));
assertThat(collection, not(hasItem("zz")));

Check if multiple elements are in a collection

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItems("cd", "ef"));

Check all elements in a collection – with strict order

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, contains("ab", "cd", "ef"));

Check all elements in a collection – with any order

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, containsInAnyOrder("cd", "ab", "ef"));

Check if collection is empty

List<String> collection = Lists.newArrayList();
assertThat(collection, empty());

Check if array is empty

String[] array = new String[] { "ab" };
assertThat(array, not(emptyArray()));

Check if Map is empty

Map<String, String> collection = Maps.newHashMap();
assertThat(collection, equalTo(Collections.EMPTY_MAP));

Check if Iterable is empty

Iterable<String> collection = Lists.newArrayList();
assertThat(collection, emptyIterable());

Check size of a collection

List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasSize(3));

Checking size of an iterable

Iterable<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, Matchers.<String> iterableWithSize(3));

Check condition on every item

List<Integer> collection = Lists.newArrayList(15, 20, 25, 30);
assertThat(collection, everyItem(greaterThan(10)));

3. Conclusion

This format is an experiment – I’m publishing some of my internal development cookbooks on a given topic – Google Guava and now Hamcrest. The goal is to have this information readily available online – and to add to it whenever I run into a new useful example.

The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven-based project, so it should be easy to import and run as it is.

Related posts:

Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Perform Naive String Matching
Spring Boot - Build Systems
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Spring Boot - Enabling Swagger2
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Hướng dẫn sử dụng String Format trong Java
Using a Spring Cloud App Starter
Login For a Spring Web App – Error Handling and Localization
Java Program to Perform the Shaker Sort
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Java Program to Implement Attribute API
Refactoring Design Pattern với tính năng mới trong Java 8
Debug a HttpURLConnection problem
Java Program to Find Median of Elements where Elements are Stored in 2 Different Arrays
Compact Strings in Java 9
Get the workstation name or IP
Java Program to Implement Singly Linked List
Spring WebClient and OAuth2 Support
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Check whether Directed Graph is Connected using BFS
How to use the Spring FactoryBean?
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Java Program to Generate a Sequence of N Characters for a Given Specific Case
HashMap trong Java hoạt động như thế nào?
Guide to @ConfigurationProperties in Spring Boot
Database Migrations with Flyway
Java Program to Implement LinkedList API
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Compute Cross Product of Two Vectors
A Guide to Java SynchronousQueue
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)