Home Java javaTutorial How to Calculate String Similarity in Java Using the Levenshtein Distance?

How to Calculate String Similarity in Java Using the Levenshtein Distance?

Nov 24, 2024 am 08:30 AM

How to Calculate String Similarity in Java Using the Levenshtein Distance?

Similarity String Comparison in Java

Understanding the Need for Similarity Measures

When working with text data, it becomes crucial to assess the similarity between strings. This can prove beneficial in tasks such as identifying duplicate content, finding the most similar search results, or even extracting meaningful information from text. Fortunately, there are efficient and well-established methods in Java for calculating string similarity.

Introducing the Similarity Function

The most common approach to string comparison involves calculating a similarity index that quantifies the degree of resemblance between two strings. A widely used similarity measure is the Levenshtein Distance, which calculates the minimum number of edits (insertions, deletions, or substitutions) required to transform one string into the other. This distance metric is typically normalized to a range between 0 and 1, where a higher value indicates greater similarity.

Implementing the Levenshtein Distance

One way to compute the Levenshtein Distance is by using the **String.getLevenshteinDistance()** method provided by the **Apache Commons Text** library, which implements the standard Levenshtein algorithm. Alternatively, you can also manually implement the algorithm as shown in the code below:

public static int editDistance(String s1, String s2) {
  int n = s1.length() + 1;
  int m = s2.length() + 1;
  int[][] matrix = new int[n][m];

  for (int i = 0; i < n; i++) {
    matrix[i][0] = i;
  }

  for (int j = 0; j < m; j++) {
    matrix[0][j] = j;
  }

  for (int i = 1; i < n; i++) {
    for (int j = 1; j < m; j++) {
      int cost = (s1.charAt(i - 1) == s2.charAt(j - 1)) ? 0 : 1;
      matrix[i][j] = Math.min(
        matrix[i - 1][j] + 1, // deletion
        Math.min(
          matrix[i][j - 1] + 1, // insertion
          matrix[i - 1][j - 1] + cost // substitution
        )
      );
    }
  }

  return matrix[n - 1][m - 1];
}
Copy after login

Calculating the Similarity Index

Once the Levenshtein Distance is computed, the similarity index can be obtained by normalizing it to the length of the longer string:

public static double similarity(String s1, String s2) {
  double longerLength = Math.max(s1.length(), s2.length());
  return 1.0 - (editDistance(s1, s2) / longerLength);
}
Copy after login

Conclusion

By implementing the Levenshtein Distance and the similarity function in Java, you gain a powerful tool for assessing the similarity between strings. This technique finds numerous applications in natural language processing, data analysis, and other domains where comparing textual content is essential.

The above is the detailed content of How to Calculate String Similarity in Java Using the Levenshtein Distance?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles