This post will calculate the similarity between two Strings in Java.

There are several good algorithms like Levenshtein distance and Jaro-Winkler distance which can be used to calculate the similarity between two strings. We can implement these algorithms ourselves, or use the implementation offered by third-party libraries.

1. Custom Implementation

The Levenshtein distance (or Edit distance) algorithm tells how different two strings are from one another by counting the minimum number of operations required to transform one string to another.

We can use Levenshtein distance to determine the similarity between two strings. The following code implements Levenshtein distance and uses it to calculate the similarity between two strings in the range [0, 1]. The code can be easily modified to calculate similarity in percentage.

Download  Run Code

2. Using Apache Commons Library

Apache Commons Lang StringUtils utility class provides various algorithms to calculate the similarity between two strings.

1. StringUtils.getLevenshteinDistance() method

To find the Levenshtein distance between two strings, we can use the StringUtils.getLevenshteinDistance() method which returns the minimum number of operations required to transform one string to another.

Download Code

2. StringUtils.getJaroWinklerDistance() method

To calculate the Jaro-Winkler distance between two strings, we can use the StringUtils.getJaroWinklerDistance() method. The Jaro measure is the weighted sum of the percentage of matched characters from each file and transposed characters. Winkler increased this measure for matching initial characters.

Download Code

That’s all about calculating similarity between two Strings in Java.