0

I need to compare the fields and depending on that if its true then update a boolean variable and if its false then capture this field and get the label and append it to a string. I have like 10-12 field values to compare, so is there a way to minimize the number of If statements we use?

If(obj1.var1 == obj2.var1){
  booleanVar+= true
  }else{
   stringVar+=obj1.var1
    }
If(obj1.var2 == obj2.var2){
  booleanVar+= true
  }else{
   stringVar+=obj1.var2
    }
'
'
'
'
'
If(obj1.var10 == obj2.var10){
  booleanVar+= true
  }else{
   stringVar+=obj1.var10
    } 
2
  • 1
    Does this answer help?
    – TSmith
    Jan 4, 2022 at 11:13
  • As described in the link I can add the code which is repeating in a new method and pass fields as params and make a call to this. But I am only comparing some specific fields of a object not all the fields. How do I iterate the method with only these specific params. Any inputs pls
    – Raham
    Jan 4, 2022 at 11:24

1 Answer 1

0

A generic way to do this would be to convert your data to Map objects, and compare:

Map<String, Object> obj1Map = (Map<String, Object>)JSON.deserializeUntyped(JSON.serialize(obj1));
Map<String, Object> obj2Map = (Map<String, Object>)JSON.deserializeUntyped(JSON.serialize(obj2));
Set<String> allKeys = obj1Map.keySet().clone();
allKeys.addAll(obj2Map.keySet().clone());
String[] diff = new String[0];
Boolean match = false;
for(String key: allKeys) {
  if(obj1Map.get(key) == obj2Map.get(key)) {
    match = true;
  } else {
    diff.add(''+obj1Map.get(key));
  }
}

This code presumes that obj1 and obj2 are not null, are objects, and are not primitive values, List objects, or Set objects.

If you are using an sObject, you can instead use getPopulatedFieldsAsMap, which has better performance than JSON.serialize/JSON.deserializeUntyped, and preserves the original data types for things like date values.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .