eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Introduction

Groovy provides a substantial number of methods enhancing Java’s core capabilities.

In this tutorial, we’ll show how Groovy does this when checking for an element and finding it in several types of collections.

2. Test If Element Is Present

First, we’ll focus on just testing if a given collection contains an element.

2.1. List

Java itself provides several ways of checking for an item in a list with java.util.List:

  • The contains method
  • The indexOf method

As Groovy is a Java-compatible language, we can safely use them.

Let’s take a look at an example:

def "whenListContainsElement_thenCheckReturnsTrue"() {
    given:
    def list = ['a', 'b', 'c']

    expect:
    list.indexOf('a') > -1
    list.contains('a')
}

Apart from that, Groovy introduces the membership operator:

element in list

It’s one of many syntactic sugar operators provided by Groovy. With its help, we can simplify our code:

def "whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue"() {
    given:
    def list = ['a', 'b', 'c']

    expect:
    'a' in list
}

2.2. Set

As with the previous example, we can use the java.util.Set#contains method and the in operator:

def "whenSetContainsElement_thenCheckReturnsTrue"() {
    given:
    def set = ['a', 'b', 'c'] as Set

    expect:
    set.contains('a')
    'a' in set
}

2.3. Map

In the case of a Map, we can check for either the key or value directly:

def "whenMapContainsKeyElement_thenCheckReturnsTrue"() {
    given:
    def map = [a: 'd', b: 'e', c: 'f']

    expect:
    map.containsKey('a')
    !map.containsKey('e')
    map.containsValue('e')
}

Or use membership operator to find the matching key:

def "whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue"() {
    given:
    def map = [a: 'd', b: 'e', c: 'f']

    expect:
    'a' in map
    'f' !in map
}

When used with maps, we should use the membership operator with care because this operator is a bit confusing to use with boolean values. Rather than testing for the presence of the key, the underlying mechanism retrieves the corresponding value from the map and just casts it to boolean:

def "whenMapContainsFalseBooleanValues_thenCheckReturnsFalse"() {
    given:
    def map = [a: true, b: false, c: null]

    expect:
    map.containsKey('b')
    'a' in map
    'b' !in map // get value of key 'b' and does the assertion
    'c' !in map
}

As we might see in the above example, it’s also a bit hazardous to use with null values either for the same reason. Groovy casts both false and null to boolean false.

3. All Match and Any Match

In most cases, we deal with collections composed of more complex objects. In this section, we’ll show how to check if the given collection contains at least one matching element or if all elements match a given predicate.

Let’s start by defining a simple class that we’ll use throughout our examples:

class Person {
    private String firstname
    private String lastname
    private Integer age

    // constructor, getters and setters
}

3.1. List/Set

This time, we’ll use a simple list of Person objects:

private final personList = [
  new Person("Regina", "Fitzpatrick", 25),
  new Person("Abagail", "Ballard", 26),
  new Person("Lucian", "Walter", 30),
]

As we mentioned before, Groovy is a Java-compatible language, so let’s first create an example using the Stream API introduced by Java 8:

def "givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList"() {
    expect:
    personList.stream().anyMatch { it.age > 20 }
    !personList.stream().allMatch { it.age < 30 }
}

We can also use the Groovy methods DefaultGroovyMethods#any and DefaultGroovyMethods#every that perform the check directly on the collection:

def "givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList"() {
    expect:
    personList.any { it.age > 20 }
    !personList.every { it.age < 30 }
}

3.2. Map

Let’s start by defining a Map of Person objects mapped by Person#firstname:

private final personMap = [
  Regina : new Person("Regina", "Fitzpatrick", 25),
  Abagail: new Person("Abagail", "Ballard", 26),
  Lucian : new Person("Lucian", "Walter", 30)
]

We can evaluate it by either its keys, values, or by whole entries. Again, let’s first use the Stream API:

def "givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap"() {
    expect:
    personMap.keySet().stream()
             .anyMatch { it == "Regina" }
    !personMap.keySet().stream()
              .allMatch { it == "Albert" }
    !personMap.values().stream()
              .allMatch { it.age < 30 }
    personMap.entrySet().stream()
             .anyMatch { it.key == "Abagail" && it.value.lastname == "Ballard" }
}

And then, the Groovy Collection API:

def "givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap"() {
    expect:
    personMap.keySet().any { it == "Regina" }
    !personMap.keySet().every { it == "Albert" }
    !personMap.values().every { it.age < 30 }
    personMap.any { firstname, person -> firstname == "Abagail" && person.lastname == "Ballard" }
}

As we can see, Groovy not only adequately replaces the Stream API when manipulating maps but also allows us to perform a check directly on the Map object instead of using the java.util.Map#entrySet method.

4. Find One or More Elements in a Collection

4.1. List/Set

We can also extract elements using predicates. Let’s start with the familiar Stream API approach:

def "givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements"() {
    expect:
    personList.stream().filter { it.age > 20 }.findAny().isPresent()
    !personList.stream().filter { it.age > 30 }.findAny().isPresent()
    personList.stream().filter { it.age > 20 }.findAll().size() == 3
    personList.stream().filter { it.age > 30 }.findAll().isEmpty()
}

As we can see, the above example uses java.util.Optional for finding a single element as the Stream API forces that approach.

On the other hand, Groovy offers a much more compact syntax:

def "givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements"() {
    expect:
    personList.find { it.age > 20 } == new Person("Regina", "Fitzpatrick", 25)
    personList.find { it.age > 30 } == null
    personList.findAll { it.age > 20 }.size() == 3
    personList.findAll { it.age > 30 }.isEmpty()
}

By using Groovy’s API, we can skip creating a Stream and filtering it.

4.2. Map

In the case of a Map, there are several options to choose from. We can find elements amongst keys, values or complete entries. As the first two are basically a List or a Set, in this section we’ll only show an example of finding entries.

Let’s reuse our personMap from earlier:

def "givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements"() {
    expect:
    personMap.entrySet().stream()
             .filter { it.key == "Abagail" && it.value.lastname == "Ballard" }
             .findAny()
             .isPresent()

    personMap.entrySet().stream()
             .filter { it.value.age > 20 }
             .findAll()
             .size() == 3
}

And again, the simplified Groovy solution:

def "givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements"() {
    expect:
    personMap.find { it.key == "Abagail" && it.value.lastname == "Ballard" }
    personMap.findAll { it.value.age > 20 }.size() == 3
}

In this case, the benefits are even more significant. We skip the java.util.Map#entrySet method and use a closure with a function provided on the Map.

5. Conclusion

In this article, we presented how Groovy simplifies checking for elements and finding them in several types of collections.

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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 – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)