Example usage for java.util Collections binarySearch

List of usage examples for java.util Collections binarySearch

Introduction

In this page you can find the example usage for java.util Collections binarySearch.

Prototype

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

Source Link

Document

Searches the specified list for the specified object using the binary search algorithm.

Usage

From source file:org.openvpms.web.component.im.query.PageLocator.java

/**
 * Returns the page that an object would fall on.
 *
 * @return the page that an object would fall on, if present
 *//*from  w ww  . ja  v  a 2s  .  co m*/
public int getPage() {
    if (!initialised) {
        query.add(new NodeSortConstraint("id"));
        comparators.addComparator(ID);
        initialised = true;
    }
    int result = 0;
    ArchetypeQueryResultSet<ObjectSet> set = new ArchetypeQueryResultSet<ObjectSet>(query, pageSize,
            new ObjectSetQueryExecutor());

    while (set.hasNext()) {
        IPage<ObjectSet> page = set.next();
        int index = Collections.binarySearch(page.getResults(), keySet, comparators);
        if (index >= 0) {
            break;
        } else {
            index = -index - 1;
            if (index < page.getResults().size()) {
                // item would be on this page, but is not present
                break;
            }
        }
        ++result;
    }
    return result;
}

From source file:com.icesoft.icefaces.tutorial.component.autocomplete.AutoCompleteBean.java

/**
 * Utility method for building the match list given the current value of the
 * SelectInputText component.//from   ww w  . j a  v a2s.c  o m
 *
 * @param event
 */
private void setMatches(ValueChangeEvent event) {

    Object searchWord = event.getNewValue();
    int maxMatches = ((SelectInputText) event.getComponent()).getRows();
    List matchList = new ArrayList(maxMatches);

    try {

        int insert = Collections.binarySearch(dictionary, searchWord, AutoCompleteDictionary.LABEL_COMPARATOR);

        // less then zero if wer have a partial match
        if (insert < 0) {
            insert = Math.abs(insert) - 1;
        }

        for (int i = 0; i < maxMatches; i++) {
            // quit the match list creation if the index is larger then
            // max entries in the dictionary if we have added maxMatches.
            if ((insert + i) >= dictionary.size() || i >= maxMatches) {
                break;
            }
            matchList.add(dictionary.get(insert + i));
        }
    } catch (Throwable e) {
        log.error("Erorr finding autocomplete matches", e);
    }
    // assign new matchList
    if (this.matchesList != null) {
        this.matchesList.clear();
        this.matchesList = null;
    }
    this.matchesList = matchList;
}

From source file:org.icefaces.sample.location.CityDictionary.java

/**
 * Generates a short list of cities that match the given searchWord.  The
 * length of the list is specified by the maxMatches attribute.
 *
 * @param searchWord city name to search for
 * @param maxMatches max number of possibilities to return
 * @return list of SelectItem objects which contain potential city names.
 */// w w w  . ja v a  2s.c om
public ArrayList generateCityMatches(String searchWord, int maxMatches) {

    ArrayList matchList = new ArrayList(maxMatches);

    // ensure the autocomplete search word is present
    if ((searchWord == null) || (searchWord.trim().length() == 0)) {
        return matchList;
    }

    try {

        int insert = Collections.binarySearch(cityDictionary, new SelectItem("", searchWord), LABEL_COMPARATOR);

        // less then zero if we have a partial match
        if (insert < 0) {
            insert = Math.abs(insert) - 1;
        }

        for (int i = 0; i < maxMatches; i++) {
            // quit the match list creation if the index is larger than
            // max entries in the cityDictionary if we have added maxMatches.
            if ((insert + i) >= cityDictionary.size() || i >= maxMatches) {
                break;
            }
            matchList.add(cityDictionary.get(insert + i));
        }
    } catch (Throwable e) {
        log.error(MessageBundleLoader.getMessage("find.findingMatches"), e);
    }
    // assign new matchList
    return matchList;
}

From source file:com.urbantamil.projmadurai.MaduraiBookCoverFragment.java

private String getGenreColorCode(String genre) {
    int pos = Collections.binarySearch(genre_list, genre, utf8.comparator);
    pos = Math.max(pos, 0);// ww w . j  av  a2  s .c om
    // 0-based
    return String.valueOf(pos % MAX_COLORS);
}

From source file:mondrian.util.UtilCompatibleJdk15.java

public <T extends Comparable<T>> int binarySearch(T[] ts, int start, int end, T t) {
    final int i = Collections.binarySearch(Arrays.asList(ts).subList(start, end), t,
            RolapUtil.ROLAP_COMPARATOR);
    return (i < 0) ? (i - start) : (i + start);
}

From source file:psiprobe.beans.LogResolverBean.java

/**
 * Gets the log sources./*from  w ww. j  av  a2s  .c  o  m*/
 *
 * @return the log sources
 */
public List<LogDestination> getLogSources() {
    List<LogDestination> sources = new LinkedList<>();

    List<LogDestination> allAppenders = getAllLogDestinations();
    if (allAppenders != null) {
        LogComparator cmp = new LogSourceComparator();

        Collections.sort(allAppenders, cmp);
        for (LogDestination dest : allAppenders) {
            if (Collections.binarySearch(sources, dest, cmp) < 0) {
                sources.add(new DisconnectedLogDestination(dest));
            }
        }
    }
    return sources;
}

From source file:edu.scripps.fl.collections.FuzzyMap.java

@Override
@SuppressWarnings("unchecked")
public V get(Object key) {
    if (list.isEmpty())
        return null;
    int idx = Collections.binarySearch((List) list, key, comparator);
    if (idx < 0) {
        idx = -1 * idx - 2;//from w  w  w.  ja v  a  2  s.  c o  m
        if (idx < 0)
            idx = 0;
    }
    Map.Entry<K, V> entry = list.get(idx);
    return entry.getValue();
}

From source file:org.openvpms.web.workspace.workflow.scheduling.Schedule.java

/**
 * Determines if the schedule has an event that intersects the specified
 * event.//  w  w  w  . j  ava 2s.co  m
 *
 * @param event the event
 * @return {@code true} if the schedule has an intersecting event
 */
public boolean hasIntersectingEvent(PropertySet event) {
    return Collections.binarySearch(events, event, intersectComparator) >= 0;
}

From source file:com.projity.interval.ValueObjectForIntervalTable.java

/**
 * A factory method returning a new value at a given date
 * @param start/*from   w w w  .  j av  a2 s  . com*/
 * @return
 * @throws InvalidValueObjectForIntervalException
 */
public ValueObjectForInterval newValueObject(long start) throws InvalidValueObjectForIntervalException {
    ValueObjectForInterval newOne = createValueObject(start);

    int index = Collections.binarySearch(valueObjects, newOne, newOne); // find where to insert
    if (index < 0) { // if doesn't already exist
        if (valueObjects.isEmpty()) {
            valueObjects.add(newOne);
            newOne.setEnd(DateTime.getMaxDate().getTime());
        } else {
            if (index == -1) {
                index = -2;
            }
            ValueObjectForInterval previous = (ValueObjectForInterval) valueObjects.get(-index - 2); // get previous element
            valueObjects.add(-index - 1, newOne); // add new in place
            newOne.setEnd(previous.getEnd()); //set new one's end to prevous end
            previous.setEnd(start); // set previous end to this start
        }
    } else { // not allowed to make duplicate, so send back error
        if (!Environment.isNoPodServer() || index != valueObjects.size() - 1)
            throw new InvalidValueObjectForIntervalException(
                    Messages.getString("ValueObjectForIntervalTable.ThatEffectiveDateIsAlreadyInTheTable")); //$NON-NLS-1$
        ValueObjectForInterval found = (ValueObjectForInterval) valueObjects.get(index);
        found.setStart(newOne.getEnd());
        valueObjects.add(index, newOne);
    }
    removeZeros();
    return newOne;
}

From source file:org.apache.hadoop.hdfs.protocol.LocatedBlocks.java

/**
 * Find block containing the specified offset, or insertion point (encoded as
 * -i-1) of the given offset among starting offsets of the blocks if there is
 * no exact match. A nonnegative return value means an exact match.
 *
 * @return the index of the block starting with the given offset if there is
 *         an exact match, or <b>-i-1</b>, where i is is the insertion point
 *         of the given offset (as defined in
 *         {@link Collections#binarySearch(List, Object, Comparator)}).
 *//*from  w w w .  j  a  v a2s. c  om*/
protected int binarySearchBlockStartOffsets(long offset) {
    LocatedBlock key = new LocatedBlock();
    key.setStartOffset(offset);
    return Collections.binarySearch(blocks, key, BLOCK_START_OFFSET_COMPARATOR);
}