I have used the .equals method to search for a String in an ArrayList, but the user has to write the exact name of the String. Is there a way to show the String that matches the user input containing ? If you for example search for 'Djang' and the String you are trying to find is 'Django'.
2 Answers
You should check out the Levenshtein Distance. It measures how far away a string is from another string. There is even a Java implementation in Wikibooks.
Then, it's a matter of sorting and finding the minimum.
list.stream()
.sort(Comparator.comparing(
s -> LevenshteinDistance.computeLevenshteinDistance(s, input))
.findFirst();
From there, it's also possible to filter to add an upper bound on the acceptable distance to prevent all inputs from returning a result.
list.stream()
.sort(Comparator.comparing(
s -> LevenshteinDistance.computeLevenshteinDistance(s, input))
.filter(s -> LevenshteinDistance.computeLevenshteinDistance(s, input) < limit)
.findFirst();
1 Comment
LevenshteinDistance is a good point. But I think the implements is not that good. by using LevenshteinDistance.computeLevenshteinDistance directly in the comparing, this costly method would be called many more times. Maybe this can be done by .filter first, or use a map to store string and the metric.try the String.contains() method
public boolean contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values.
Parameters: s - the sequence to search for
Returns: true if this string contains s, false otherwise
Throws: NullPointerException - if s is null
Since: 1.5
For example:
String myString = "Django"
public boolean stringCatcher(String userInput) {
return myString.contains(userInput);
}
then passing Djang to stringCatcher() would result in a true value being returned.
String#contains