The quickest way without writing any code is Lombok

Lombok is one of the most used libraries in java and it takes a lot of Boilerplate code off your projects. If you need to read more on what it can and does, go here.

The way to implement what you need is pretty straightforward:

// Generate the equals and HashCode functions and Include only the fields that I annotate with Include
@EqualsAndHashCode(onlyExplicitlyIncluded = true) 
@Getter // Generate getters for each field
@Setter // Generate setters for each field
public class Class1
{

  @EqualsAndHashCode.Include // Include this field
  private Long identity;
  
  private String testStr1; // This field is not annotated with Include so it will not be included in the functions.

  // ... any other fields
}

Lombok can do a lot more than this. For more information on @EqualsAndHashCode refer to this.

You can always use @EqualsAndHashCode.Exclude for a quicker solution to your use case:

@EqualsAndHashCode
@Getter // Generate getters for each field
@Setter // Generate setters for each field
public final class Class1 {
  private String a;
  private String b;
  private String c;
:
:
:

  private String z;

  @EqualsAndHashCode.Exclude
  private Date createdAt; 
  @EqualsAndHashCode.Exclude
  private Date updatedAt; 
} 
Answer from Renis1235 on Stack Overflow
Top answer
1 of 6
9

The quickest way without writing any code is Lombok

Lombok is one of the most used libraries in java and it takes a lot of Boilerplate code off your projects. If you need to read more on what it can and does, go here.

The way to implement what you need is pretty straightforward:

// Generate the equals and HashCode functions and Include only the fields that I annotate with Include
@EqualsAndHashCode(onlyExplicitlyIncluded = true) 
@Getter // Generate getters for each field
@Setter // Generate setters for each field
public class Class1
{

  @EqualsAndHashCode.Include // Include this field
  private Long identity;
  
  private String testStr1; // This field is not annotated with Include so it will not be included in the functions.

  // ... any other fields
}

Lombok can do a lot more than this. For more information on @EqualsAndHashCode refer to this.

You can always use @EqualsAndHashCode.Exclude for a quicker solution to your use case:

@EqualsAndHashCode
@Getter // Generate getters for each field
@Setter // Generate setters for each field
public final class Class1 {
  private String a;
  private String b;
  private String c;
:
:
:

  private String z;

  @EqualsAndHashCode.Exclude
  private Date createdAt; 
  @EqualsAndHashCode.Exclude
  private Date updatedAt; 
} 
2 of 6
8

If overriding Object::equals and Object::hashCode is not an option, we can use the Comparator API to construct a corresponding comparator:

final Comparator<Class1> comp = Comparator.comparing(Class1::getA)
        .thenComparing(Class1::getB)
        .thenComparing(Class1::getC)
        .
        .
        .
        .thenComparing(Class1::getZ);

Unfortunately, there is no way to do this without comparing all fields that should be equal.

Discussions

java - Check if two objects are equal excluding a few properties - Stack Overflow
You can also check the 'Comparable' .../docs/api/java/lang/Comparable.html ... If I have a variable x then I do something and ask "did x change?", you can't answer that question without knowing the initial and final value of x. Therefore if you want to check if certain fields changed then you must read and compare those fields initial and final values. You can add some efficiency by caching hash codes of the objects, and if the ... More on stackoverflow.com
🌐 stackoverflow.com
clean code - How to define what fields to check for equality? - Software Engineering Stack Exchange
I have an odd conceptual question, It's not about a specific incident, just a general best-practices approach. I have asked myself on occasion when defining java Equal methods, what makes two ob... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
[JUnits] How to compare 2 complex objects without overriding toequals/hashcode methods?
Serialize both to JSON with Gson and pretty printing turned on. Now just compare the strings and get a nice human-readable output. More on reddit.com
🌐 r/java
17
4
February 7, 2015
[Solved] Compare two objects excluding some fields - Java
Anamika Patel Asks: Compare two objects excluding some fields - Java I need to compare two objects of the same class excluding some fields. public final class Class1 { private String a; private String b; private String c; : : : private String z; private Date createdAt; private... More on solveforum.com
🌐 solveforum.com
0
0
May 17, 2017
🌐
GitHub
github.com › SQiShER › java-object-diff › issues › 44
How to ignore certain fields for comparison? · Issue #44 · SQiShER/java-object-diff
April 4, 2012 - I want to compare 2 objects but wanted to specify some fields that should be ignored for comparison. Can it be done?
Published   Dec 07, 2012
🌐
How to do in Java
howtodoinjava.com › home › java basics › java object equality without public fields or getters
Java Object Equality without Public Fields or Getters
September 11, 2024 - To exclude certain fields from the comparison, we can pass a list of field names as the third parameter in the method. List<String> excludeFields = List.of("fieldname1", "fieldname2"); boolean isEqual = EqualsBuilder.reflectionEquals(firstObject, ...
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-2.4 › org › apache › commons › lang › builder › EqualsBuilder.html
EqualsBuilder (Commons Lang 2.4 API) - Apache Commons
January 13, 2008 - Superclass fields will be included. Parameters: lhs - this object · rhs - the other object · Returns: true if the two Objects have tested equals. public static boolean reflectionEquals(java.lang.Object lhs, java.lang.Object rhs, java.util.Collection excludeFields) This method uses reflection to determine if the two Objects are equal.
Top answer
1 of 2
3

I think if there were a one-size-fits-all way to compare objects, then Java (or any language) would make it the default, no?

Equality - like hashing and comparison - should be fast, simple and most importantly referentially transparent.

In the end, the question of what exactly the equals method is for is important. If you don't know, then just leave it as is. Physical comparison makes sense in many use cases, particularly if you have control over when objects are created vs. when they are reused.

Also, rather than trying to design comparison functions meaningful for all cases, write code using things like Comparator and let calling code inject whatever makes the most sense at the call site.

2 of 2
3

First of all, there are two kinds of classes:

  • Classes with "value-type" semantics.
  • Classes with "reference" semantics.

You can google these terms to find information about precisely what they mean, and how they differ from each other, for your language of choice.

Every single class with "value-type" semantics must have an equals() method, and this method must take into consideration every single one of its fields, or at least give the illusion that it does so. If it is expensive, bite the bullet and spend clock cycles lavishly, because it is necessary.

Classes with "reference" semantics do not need an equals() method. I would not go as far as to say that they should not have such a method, but if they are to have one, it should be thought of as a utility / helper method which is going to be used in some weird way which is unrelated to the original intent of equals. That's because under normal circumstances, these objects are compared by reference, not by value.

Reference equality is checked using the == operator in Java, while in C#, where the == operator may be overloaded, we use System.Object.ReferenceEquals(). (Though, again, you are not supposed to overload the == operator of a reference-semantics class.)

Incidentally, the kinds of classes that are complex and expensive to check for equality usually tend to be classes with reference semantics, so they do not need an equals() method. And generally, if you have any doubts or second thoughts as to how the equals() method should be implemented, this is a good indication that what you have in your hands is a reference-semantics class, not a value-type-semantics class.

As for hashCode(), the only objects that should implement it are objects that not only have value semantics, but are also immutable. This is because hash containers generally obtain the hash code of an object once, and then cache it for as long as the object resides in the container, so if the object undergoes a mutation, the contents of the object will be in conflict with the cached hash code. It is a very common newbie bug to use a non-immutable object as a key to a hashmap, and a very hard one to track down unless you know where to look first: the immutability of the class used as the key.

So, every class which is not immutable should have a hashCode() method coded as follows:

public int hashCode()
{
    assert false; //OMG! hashCode() was invoked on mutable object!
}

So, since only immutable classes should implement hashCode(), ensuring that it works in a way which is in agreement with how equals() works is pretty straightforward, and probably a lot more simple than what you may have feared.

Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › comparing objects in java
Comparing Objects in Java | Baeldung
October 10, 2025 - However, if we add too many nullable fields to our class, it can become really messy. Using the Objects#equals method in our equals() implementation is much cleaner, and improves readability: ... Comparison logic can also be used to place objects in a specific order.
🌐
Baeldung
baeldung.com › home › testing › ignoring fields during comparison using assertj
Ignoring Fields During Comparison Using AssertJ | Baeldung
July 19, 2024 - Firstly, let’s see how we can specify one or more fields to ignore when comparing actual and expected objects. Here, we can use the APIs ignoringFields() method. It lets us specify which fields should be ignored during the comparison.
🌐
Baeldung
baeldung.com › home › java › using the apache commons lang 3 for comparing objects in java
Using the Apache Commons Lang 3 for Comparing Objects in Java | Baeldung
April 8, 2016 - Suppose we want to exclude a specific discovered field from the comparison. In that case, we can use the @DiffExclude annotation to mark the fields we wish to exclude from the ReflectionDiffBuilder‘s use.
🌐
EqualsVerifier
jqno.nl › equalsverifier › manual › ignoring-fields
Ignoring fields - EqualsVerifier
Like withIgnoredFields, withOnlyTheseFields accepts a varargs argument, so you can specify as few or as many fields as you need. Again, EqualsVerifier throws an exception if any of the fields doesn’t exist. Java has the transient keyword to exclude fields from serialization, and JPA has the @Transient annotation to exclude fields from being persisted.
🌐
Apache Commons
commons.apache.org › proper › commons-lang › apidocs › org › apache › commons › lang3 › builder › EqualsBuilder.html
EqualsBuilder (Apache Commons Lang 3.20.0 API)
Non-primitive fields are compared using equals(). If the TestTransients parameter is set to true, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the Object. Static fields will not be tested.
🌐
Codepudding
codepudding.com › other › 238584.html
Compare two objects excluding some fields - Java-CodePudding
. . .thenComparing(Class1::getZ); Unfortunately, there is no way to do this without comparing all fields that should be equal. ... import java.util.Date; import java.util.Objects; public final class Class1 { private String a; private String b; private String c; private String z; private Date ...
🌐
DZone
dzone.com › testing, deployment, and maintenance › testing, tools, and frameworks › how to verify equality without equals method
How to Verify Equality Without Equals Method
April 27, 2016 - Assertions in tests often require ... child fields have the same values. Of course it doesn’t make sense to create equals only for testing assertions. Sometimes we also have nested types to compare. And what about comparison of arrays or lists during testing? Luckily there is a very neat library called Unitils. It provides various testing helpers for Hibernate, Database and I/O testing or mocking. But I was only using a module called Reflection assert. It makes camparison of Java objects a piece of ...
🌐
SmartBear Community
community.smartbear.com › smartbear community › readyapi › readyapi questions
Compare two REST response and ignore some fields | SmartBear Community
July 14, 2020 - private void compare(def expected, def actual, def ignore) { def expectedParse = new JsonSlurper().parseText(expected) def actualParse = new JsonSlurper().parseText(actual) def parentnode def dynmaicparent def ignorefields = ignore.split(',') for(int i =0; i <ignorefields.size(); i++){ values=ignorefields[i].trim() //log.info( i + "id to remove " + values) if(values.contains('.')){ parentnode = values.tokenize(".")[0] childnode = values.substring(parentnode.length()+1) log.info( expectedParse.get(parentnode).size()) for(int j =0; j <expectedParse.get(parentnode).size(); j++){ expectedParse.get
🌐
Java Code Geeks
javacodegeeks.com › home › core java
AssertJ Ignore Fields Comparison Example - Java Code Geeks
October 25, 2024 - - the introspection strategy used was: DefaultRecursiveComparisonIntrospectionStrategy at org.zheng.demo.AssertJApp.main(AssertJApp.java:27) Line 4-8, 10-12: AssertJ error message is readable and explains the failure details. In this example, I demonstrated Assertj ignore fields comparison class RecursiveAssertionAssert with the following methods: ignoringFields – recursive assertion ignores the specified fields in the object.
🌐
solveForum
solveforum.com › home › forums › solveforum all topics › tech forum
[Solved] Compare two objects excluding some fields - Java | solveForum
May 17, 2017 - Anamika Patel Asks: Compare two objects excluding some fields - Java I need to compare two objects of the same class excluding some fields. public final class Class1 { private String a; private String b; private String c; : : : private String z; private Date createdAt; private...