Binary Searching : Collections Search « Collections « Java Tutorial






import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MainClass {
  public static void main(String args[]) {
    String str[] = { "B", "H", "L", "M", "I", "N", "R" };
    // Convert to list
    List list = new ArrayList(Arrays.asList(str));
    // Ensure list sorted
    Collections.sort(list);
    System.out.println("Sorted list: [length: " + list.size() + "]");
    System.out.println(list);
    // Search for element in list
    int index = Collections.binarySearch(list, "M");
    System.out.println("Found M @ " + index);
    // Search for element not in list
    index = Collections.binarySearch(list, "J");
    System.out.println("Didn't find J @ " + index);
    // Insert
    int newIndex = -index - 1;
    list.add(newIndex, "J");
    System.out.println("With J added: [length: " + list.size() + "]");
    System.out.println(list);
  }
}
Sorted list: [length: 7]
[B, H, I, L, M, N, R]
Found M @ 4
Didn't find J @ -4
With J added: [length: 8]
[B, H, I, J, L, M, N, R]








9.41.Collections Search
9.41.1.Binary Searching
9.41.2.Check whether the given Collection contains the given element instance.
9.41.3.Binary search routines
9.41.4.Return the first element in 'candidates' that is contained in source
9.41.5.Find a value of the given type in the given Collection
9.41.6.Get the difference of two collections
9.41.7.A binary search implementation.