Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This should work:</p> <pre><code> Comparator&lt;String&gt; startsWithComparator = new Comparator&lt;String&gt;() { public int compare(String currentItem, String key) { if(currentItem.startsWith(key)) { return 0; } return currentItem.compareTo(key); } }; int index = Collections.binarySearch(items, "contact.", startsWithComparator); </code></pre> <p>However sorting and then binary searching is less efficient than the single pass iteration.</p> <p><strong>Addendum:</strong></p> <p>Though the above answer helps you, here is another way (inspired from Scala, Google Collections) :</p> <pre><code>List&lt;String&gt; items = Arrays.asList("one", "two", "three", "four", "five", "six"); int index = find(items, startsWithPredicate("th")); System.out.println(index); public static Predicate&lt;String&gt; startsWithPredicate(final String key) { return new Predicate&lt;String&gt;(){ @Override public boolean apply(String item) { return item.startsWith(key); } }; } public static &lt;T&gt; int find(Collection&lt;T&gt; items, Predicate&lt;T&gt; predicate) { int index = 0; for(T item: items) { if(predicate.apply(item)) { return index; } index++; } return -1; } interface Predicate&lt;T&gt; { boolean apply(T item); } </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload