Java - Collection Framework List Searching

Introduction

You can use the following two static binarySearch() method in the Collections class to search for a key in a List.

<T> int binarySearch(List<? extends Comparable<? super T>>list, T key)
<T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

A List must be sorted in ascending order before you use the binarySearch() method.

If the key is found in the List, the method returns the index of the key in the List.

Otherwise, it returns (-(insertion index) ?1), where the insertion index is the index in the List where this key would have been placed.

If you get a negative number as the retuned value, use its absolute value as the insertion index.

This method uses the binary search algorithm to perform the search.

If the List supports random access, the search runs in log(n) time.

If the List does not support random access, the search runs in n x log(n) time.

The following code shows how to use this method:

Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("XML");
    list.add("Javascript");
    list.add("Json");
    list.add("Java");

    // Must sort before performing the binary search
    Collections.sort(list);/*from w  w  w  .j av a 2 s  . co m*/
    System.out.println("List: " + list);

    // Find Json
    int index = Collections.binarySearch(list, "Json");
    System.out.println("Json in List is at " + index);

    // Find Python
    index = Collections.binarySearch(list, "Python");
    System.out.println("Python in List is at " + index);
  }
}

Result