Search the position of the given object in the list of ordered objects. - Java java.util

Java examples for java.util:List Search

Description

Search the position of the given object in the list of ordered objects.

Demo Code


//package com.java2s;
import java.util.Comparator;
import java.util.List;

public class Main {
    /**//from  w w  w  .j  av a  2  s.  com
     * 
     * <pre>
     * This code shows how this class can be used:
     * 
     * List list = ...
     * int pos = CollectionsUtil.search(list, "abc", new Comparator() {
     *     public int compare(T o1, T o2) {
     *          String s1 = (String) o1;
     *          String s2 = (String) o2;
     *          return s1.compare(s2);
     *     }
     * });
     * if (pos >= 0) {
     *      System.out.println("The object was found in the " 
     *          + pos 
     *          + " position");
     * } else {
     *      pos = -(pos + 1);
     *      System.out.println("The object should be inserted in the " 
     *          + pos 
     *          + " position");
     * }
     * </pre>
     * 
     */
    public static int search(List list, Object value, Comparator c) {
        int low = 0;
        int high = list.size() - 1;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            Object midVal = list.get(mid);
            int cmp = c.compare(midVal, value);
            if (cmp < 0)
                low = mid + 1;
            else if (cmp > 0)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1); // key not found
    }
}

Related Tutorials