I am trying to write a quick search that searches a List<String>
Instead of looping through the list and manually checking, I want to do this using binarySearch, but I am not sure how to do it.
Old way:
for(String s : list) {
if(s.startsWith("contact.")
return true;
}
Instead I would like something like this:
Collections.sort(list);
Collections.binarySearch(list, FindContactComparator());
Can someone help me write this Comparator?
Is there any better way of doing this instead of using binarySearch?
This should work:
However sorting and then binary searching is less efficient than the single pass iteration.
Addendum:
Though the above answer helps you, here is another way (inspired from Scala, Google Collections) :
Here the thing is the find() method is not tied with your ‘matching’ logic; it just finds an element that satisfies the predicate. So you could pass on a different implementation of predicate, for ex. which can check ‘endsWith’ to find() method and it would return the found item which ends with a particular string. Further the find() method works for any type of collection; all it needs is a predicate which transforms an element of collection element type to a boolean. This multiple lines of code around a simple logic also show the Java’s lack of support for first class functions.