Java implementation of text diff library based on Myers Diff Algorithm. This is a Java port of the 1diff-ts JavaScript library.
Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.daichangya</groupId>
<artifactId>1diff-java</artifactId>
<version>1.0.0</version>
</dependency>
import diff.io.github.daichangya.CharacterDiff;
import model.io.github.daichangya.ChangeObject;
import java.util.List;
List<ChangeObject<String>> changes =
CharacterDiff.diffChars("beep boop", "beep boob blah");
for (ChangeObject<String> change : changes) {
if (change.isAdded()) {
System.out.println("+ " + change.getValue());
} else if (change.isRemoved()) {
System.out.println("- " + change.getValue());
} else {
System.out.println(" " + change.getValue());
}
}
import diff.io.github.daichangya.LineDiff;
import model.io.github.daichangya.DiffOptions;
String oldText = "line1\nline2\nline3";
String newText = "line1\nline2 modified\nline3";
List<ChangeObject<String>> changes =
LineDiff.diffLines(oldText, newText);
// With options
DiffOptions options = DiffOptions.builder()
.ignoreWhitespace(true)
.stripTrailingCr(true)
.build();
List<ChangeObject<String>> changes2 =
LineDiff.diffLines(oldText, newText, options);
import diff.io.github.daichangya.WordDiff;
String oldText = "hello world";
String newText = "hello beautiful world";
List<ChangeObject<String>> changes =
WordDiff.diffWords(oldText, newText);
import diff.io.github.daichangya.JsonDiff;
import java.util.Map;
Map<String, Object> oldObj = Map.of("name", "John", "age", 30);
Map<String, Object> newObj = Map.of("name", "John", "age", 31);
List<ChangeObject<String>> changes =
JsonDiff.diffJson(oldObj, newObj);
import patch.io.github.daichangya.PatchCreator;
String oldText = "line1\nline2\nline3";
String newText = "line1\nline2 modified\nline3";
// Create unified diff format patch
String patch = PatchCreator.createPatch("test.txt", oldText, newText);
System.out.println(patch);
import patch.io.github.daichangya.PatchApplier;
String result = PatchApplier.applyPatch(oldText, patch);
System.out.println(result);
All diff classes inherit from the Diff<T> base class, implementing the Myers Diff algorithm.
Represents a change unit in the diff:
getValue(): The changed contentisAdded(): Whether it's an additionisRemoved(): Whether it's a removalgetCount(): Number of tokensThis project is licensed under BSD-3-Clause, consistent with the original 1diff-ts project.
daichangya