How can plain string comparison be made less error prone?

77 Views Asked by At

I have a method that compares a person's name with other person's details. However, it may fail in scenarios where the middle name is included in the first name or other similar combinations.

I'm exploring potential solutions and would like to know if applying fuzzy logic is an appropriate approach, or if there's a simpler and more effective solution available. Thanks.

private boolean compareString(String compareFirstName, String compareMiddleName, String compareLastName) {
    return firstName.equalsIgnoreCase(compareFirstName) && 
middleName.equalsIgnoreCase(compareMiddleName) &&
lastName.equalsIgnoreCase(compareLastName);

}
2

There are 2 best solutions below

0
On

IMHO, you may utilize the Apache Commons Text library for fuzzy string matching. The trick here is to calculate the matching score between the string you compare and use it to benchmark the similarity.

import org.apache.commons.text.similarity.FuzzyScore;

private boolean compareNames(String firstName, String middleName, String lastName) {
    // Initialize a FuzzyScore object with a matching threshold
    FuzzyScore fuzzyScore = new FuzzyScore(0.8); // Adjust the threshold as needed

// Calculate matching scores for names
int firstNameScore = fuzzyScore.fuzzyScore(firstName, textToCompare);
int middleNameScore = fuzzyScore.fuzzyScore(middleName, textToCompare);
int lastNameScore = fuzzyScore.fuzzyScore(lastName, textToCompare);

// Check if the scores meet the threshold
return firstNameScore >= fuzzyScore.getThreshold() && middleNameScore >= fuzzyScore.getThreshold() && lastNameScore >= fuzzyScore.getThreshold();
}

You may adjust the threshold according to your scenario. Hope this might give you an idea to kick start.

0
On

"... it may fail in scenarios where the middle name is included in the first name or other similar combinations. ..."

Concatenate the values.

boolean compareString(String x, String y, String z) {
    String a = x + ' ' + y + ' ' + z,
           b = this.x + ' ' + this.y + ' ' + this.z;
    return a.equalsIgnoreCase(b);

}