How can you find the similarity rate of two objects expressed by a percentage? Read it below.
For example, I have two objects with the same object type. In this example we have an object ‘contact’.
Contact model class
Public class Contact { private String lastname; private String firstname; private String language; //getters & setters; }
Now, lets say you have two contact objects:
Contact object 1
- lastname: null
- firstname: Laurent
- language: NL
Contact object 2
- lastname: Hinoul
- firstname: Laurent
- language: NL
Now we want to know what the equality is between the two classes is, expressed in a percentage. To do so, we make use of Reflect. Copy the following class in your code;
public class Equalifier { public int equalify(Object object1, Object object2) throws InstantiationException, IllegalAccessException { Map<String, Object> obj1Fields = getFieldNamesAndValues(object1); Map<String, Object> obj2Fields = getFieldNamesAndValues(object2); int same = 0; for (Map.Entry<String, Object> entry : obj1Fields.entrySet()) { Object val1 = entry.getValue(); Object val2 = obj2Fields.get(entry.getKey()); if (String.valueOf(val1).equals(String.valueOf(val2))) { same++; } } return (int) (((double) same / (double) obj1Fields.size()) * 100); } private Map<String, Object> getFieldNamesAndValues(final Object valueObj) throws IllegalArgumentException, IllegalAccessException { Class c1 = valueObj.getClass(); Map<String, Object> fieldMap = new HashMap<String, Object>(); Field[] valueObjFields = c1.getDeclaredFields(); for (int i = 0; i < valueObjFields.length; i++) { String fieldName = valueObjFields[i].getName(); valueObjFields[i].setAccessible(true); Object newObj = valueObjFields[i].get(valueObj); fieldMap.put(fieldName, newObj); } return fieldMap; } }
Now we can test our code. Implement the following test case:
@Test public void test() throws InstantiationException, IllegalAccessException { Equalifier equalifier = new Equalifier(); Contact contact1 = new Contact(); Contact contact2 = new Contact(); contact1.setLanguage("NL"); contact1.setFirstname("Laurent"); contact2.setLanguage("NL"); contact2.setFirstname("Laurent"); contact2.setLastname("Hinoul"); assertEquals(equalifier.equalify(contact1, contact2), 66); }
The result is that the two object are 66% equal.