Groovy: remove duplicate objects from list

By , last updated August 5, 2019

Given a collection of objects with a lot of variables, how can you remove all the duplicates from the list in Groovy?

Here we will use a simple unique() method to filter out all duplicate objects.

The rules describing whether the objects are duplicates need to be implemented within a custom compareTo method.

The object that we are comparing needs to implement the Comparable interface and override its standard compareTo method.

Let’s take a look at the example object User that has a number of different parameters to describe it:

class User {
    String id
    String name
    String surname
    int phoneNumber
    Date birthday
    Date changed
}

In this example, two User objects will be duplicates only if they have the same name, surname and a birthday date. We assume users can have multiple phone numbers, ids and may change their user data as often as they wish.

Within our custom compareTo method we will define the rules that compare only name, surname and a birthday date. Use operators ?: to attach more logical rules to the compare method.

class User implements Comparable {
    String id
    String name
    String surname
    int phoneNumber
    Date birthday
    Date changed

    int compareTo(Object other) {
        name <=> other.name ?:
                surname <=> other.surname ?:
                        birthday<=> other.birthday

    }
}

The resulting list will be made unique by calling the unique() method on the list. This method will call the overridden compareTo method in User itself in Groovy.

Remember that unique() changes the original collection!

usersList.unique()