1

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'.

jsanchezs
2,0783 gold badges30 silver badges56 bronze badges
asked Dec 28, 2015 at 22:32
2
  • 1
    You could use a regular expression or something like String#contains Commented Dec 28, 2015 at 22:36
  • what do you mean by "name of the String"? Commented Dec 28, 2015 at 22:38

2 Answers 2

3

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();
Pang
10.2k146 gold badges87 silver badges126 bronze badges
answered Dec 28, 2015 at 22:51

1 Comment

The 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.
0

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.

answered Dec 28, 2015 at 22:36

1 Comment

That actually works pretty well. Guess it was kind of a noob question too, i feel like i should have known this or at least be able to search me to the answer:-). Thanks for the quick answer though!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.