How to ignore 1 field in Java equals() for custom object?

Viewed 1114

I have a Person object which has 20 fields and stored in dynamoDB. I want to create a new Person object based on some input, check if the same object exists in the Database or not. If it exists, I want to compare the 2 objects on the basis of 19 fields out of 20. The field to ignore is a boolean flag check.

I am using Lombok @Data to generate the equals method.

Is there a way to do this without having to write a full fledged overriden equals method myself ?

1 Answers

You can also use Lombok's @EqualsAndHashCode in conjunction with an exclude.

@EqualsAndHashCode
public class MyObject{

    @EqualsAndHashCode.Exclude
    Object fieldToExclude;

}

Instead of choosing which to exclude you can also opt to choose the ones you wish to include like so. All which is not annotated with Include will not be used in the equals & hashcode implementation.

@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class MyObject{

    @EqualsAndHashCode.Include
    Object fieldToInclude;

}

Lombok EqualsAndHashCode documentation

Related