I just wanted to add that StringUtils also has a convenient Levenshtein distance method since version 3.0
public static int getLevenshteinDistance(CharSequence s, CharSequence t)
After that, it is as simple as iterating through the collection and remembering the closest match:
public static Object findClosestMatch(Collection<?> collection, Object target) { int distance = Integer.MAX_VALUE; Object closest = null; for (Object compareObject : collection) { int currentDistance = StringUtils.getLevenshteinDistance(compareObject.toString(), target.toString()); if(currentDistance < distance) { distance = currentDistance; closest = compareObject; } } return closest; }
Note that the method described above requires the collection to be uptime and the toString () function to be implemented with feeling.
source share