Search code examples
stringjava-8functional-programmingstring-comparison

Comparing two strings and count differences with Stream API


Today I was trying to compare two strings with Stream API in java. Let's assume that we have two Strings:

String str1 = "ABCDEFG"
String str2 = "ABCDEEG"

We can make streams from it with:

str1.chars().stream()...
str2.chars().stream()...

And now I want to compare these string, char by char and iterate some variable when char will be different on the same position, so the result in this case will be 1, because there is one difference in this.

I was trying to do call map or forEach from first and there my journey ends, because I don't know how to get corresponding element form second stream.


Solution

  • Assuming that both the strings are of same length(integer max), you can count the differences as :

    int diffCount = (int) IntStream.range(0, str1.length())
                             .filter(i -> str1.charAt(i) != str2.charAt(i)) // corresponding characters from both the strings
                             .count();