Compare two objects excluding some fields - Java
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;
}
fastest way to compare 2 objects excluding a few properties?
It would certainly be faster if you just used reflection to create and compile a method using the above logic. This should be much faster than reflecting on each object.
How to compare Two Object -Exclude specific Properties in Comparison
I tried to develop a different solution using Expression Trees which is, in my opinion, more flexible
public class Test
{
public static void Main()
{
Address a1 = new Address();
a1.AddressID = "100";
Address a2 = new Address();
a2.AddressID = "200";
Console.WriteLine(IsAddressModified(a1,a2,a=>a.AddressID));
}
public static bool IsAddressModified(Address a1,Address a2,params Expression<Func<Address,Object>>[] props)
{
if(props == null)
return a1.Equals(a2);
foreach(Expression<Func<Address,object>> memberExpression in props)
{
MemberExpression property = memberExpression.Body as MemberExpression;
if(property != null)
{
foreach(PropertyInfo pi in typeof(Address).GetProperties())
{
// exclude all properties we passed in
if(!pi.Name.Equals(property.Member.Name))
{
var valueA1 = pi.GetValue(a1);
var valueA2 = pi.GetValue(a2);
if(valueA1 != null && valueA2 != null)
if(!valueA1.Equals(valueA2))
return true;
}
}
}
}
return false;
}
}
So what does the code?
- You can pass an array of 'properties' to the method
IsAddressModified
. These properties will be excluded while comparing. - From the Expression I extract a MemberExpression to get the Name of each Property.
- I iterate through all Properties the type
Address
has and check if it is one property to exclude. - Last but not least, I compare the property values.
Why so 'complicated' ?
With this solution you can pass as much properties into the function as you like AND you are totally type-safe during compilation.
In the Main you can see how I call this function. Even due to the fact that AddressID
of a1
and a2
differ, the function returns false, because you excluded the AddressID
.
A full compilable example can be found here
Compare Two Custom list objects by Ignoring few properties
You can create your own custom implementation of IEqualityComparer like the below:
Here is a Fiddle example where the last four employees from List1 should be returned: https://dotnetfiddle.net/f3sBLq
In this example, EmployeeComparer
inherits from IEqualityComparer<Employee>
where Employee is a class with the properties you listed (EmployeeID, Firstname, Lastname, Employmentstatus)
public class EmployeeComparer : IEqualityComparer<Employee>
{
public int GetHashCode(Employee co)
{
if (co == null)
{
return 0;
}
//You can use any property you want (other than EmployeeID for your purposes); the GetHashCode metho is used to generate an address to where the object is stored
return co.Employmentstatus.GetHashCode();
}
public bool Equals(Employee x1, Employee x2)
{
if (object.ReferenceEquals(x1, x2))
{
return true;
}
if (object.ReferenceEquals(x1, null) || object.ReferenceEquals(x2, null))
{
return false;
}
// Check for equality with all properties except for EmployeeID
return x1.Employmentstatus == x2.Employmentstatus && x1.Firstname == x2.Firstname && x1.Lastname == x2.Lastname;
}
}
Then you can use it like this:
var results = List2.Except(List1, new EmployeeComparer()).ToList();
Edit: Original question did not list ID
as property and requested how to exclude EmployeeID
which is what this answer and Fiddle link example are both based on.
Javascript- Compare 2 object excluding certain keys
You can remove uuid first than compare them.
const object1 = { uuid: '5435443', name: 'xxx', branches: [{ uuid: '643643', children: [{ uuid: '65654' /* and so on */ }] }]};
const object2 = { uuid: '7657657', name: 'xxx', branches: [{ uuid: '443444', children: [{ uuid: '09809' }] }]};
const removeUuid = o => {
if (o) {
switch (typeof o) {
case "object":
delete o.uuid;
Object.keys(o).forEach(k => removeUuid(o[k]));
break;
case "array":
o.forEach(a => removeUuid(a));
}
}
}
removeUuid(object1);
removeUuid(object2);
expect(object1).toBe(object2);
How can I check if two object's attributes are similar except for one attribute?
You can use spread (...)
before to exclude the quantity or any other properties
const { quantity: quantitya, ...a } = {
name: "Bud Lite",
price: 399,
modifiers: null,
quantity: 2,
}
const { quantity: quantityb, ...b } = {
name: "Bud Lite",
price: 399,
modifiers: null,
quantity: 1,
}
console.log(JSON.stringify(a) === JSON.stringify(b))
Related Topics
Crudrepository and Hibernate: Save(List<S>) VS Save(Entity) in Transaction
Http Post Request With Content Type Application/X-Www-Form-Urlencoded Not Working in Spring
Spring Boot @Enablescheduling Conditionally
Setting Custom Key When Pushing New Data to Firebase Database
How to Junit Test That Two List<E> Contain the Same Elements in the Same Order
Passing Empty List as Parameter to JPA Query Throws Error
How to Apply Spring Boot Filter Based on Url Pattern
Status Expected:<200> But Was:<404> in Spring Test
Intellij Compilation Error Zip End Header Not Found
How to Evaluate a Math Expression Given in String Form
Simpledateformat Producing Wrong Date Time When Parsing "Yyyy-Mm-Dd Hh:Mm"
Spring Boot Error: Java.Lang.Noclassdeffounderror: Org/Springframework/Util/Assert
Sending Variable from Adapter to Activity
How to Fetch All Links and Click Those Links One by One Using Selenium Webdriver
How to Get the Parent Element Name of a Child Element in Json
How to Create Comma Separated String in Single Quotes from Arraylist of String in Java
Java.Lang.Noclassdeffounderror: Com/Fasterxml/Jackson/Databind/Exc/Invaliddefinitionexception