Java Collection Tutorial - Java Collections.binarySearch(List <? extends T> list, T key, Comparator <? super T> c)








Syntax

Collections.binarySearch(List <? extends T> list, T key, Comparator <? super T> c) has the following syntax.

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

Example

In the following code shows how to use Collections.binarySearch(List <? extends T> list, T key, Comparator <? super T> c) method.

//from   ww w  . ja v  a  2 s.c  o m

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

public class Main {
   public static void main(String args[]) {
      // create arraylist       
      ArrayList<String>  arlst=new ArrayList<String> ();
      
      arlst.add("A");
      arlst.add("B");
      arlst.add("C");
      arlst.add("D");
      
      // search for key 
      int index=Collections.binarySearch(arlst, "D", Collections.reverseOrder());     
      
      System.out.println(index);
      
      index=Collections.binarySearch(arlst, "D");     
      
      System.out.println(index);
   }    
}

The code above generates the following result.