Java Collections binary search List

Description

Java Collections binary search List

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

public class Main {
  public static void main(String[] args) {
    // create an ArrayList<String> from the contents of colors array
    String[] colors = { "CSS", "Java", "html", "Javascript", "SQL", "C++"};
    List<String> list = new ArrayList<>(Arrays.asList(colors));

    Collections.sort(list); // sort the ArrayList
    System.out.printf("Sorted ArrayList: %s%n", list);

    printSearchResults(list, "C"); 
    printSearchResults(list, "C++"); 
    printSearchResults(list, "CSS"); 
    printSearchResults(list, "html"); 
    printSearchResults(list, "HTML"); 
    printSearchResults(list, "SQL"); 
  }/*  w  w w. j  av a2s. c  om*/
  private static void printSearchResults(List<String> list, String key) {
    int result = 0;

    System.out.printf("%nSearching for: %s%n", key);
    result = Collections.binarySearch(list, key);

    if (result >= 0)
      System.out.printf("Found at index %d%n", result);
    else
      System.out.printf("Not Found (%d)%n", result);
  }
}



PreviousNext

Related