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

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

Source Link

Document

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

Usage

From source file:rikka.materialpreference.PreferenceGroup.java

/**
 * Adds a {@link Preference} at the correct position based on the
 * preference's order.//from  w w w.  ja v  a  2 s .  c o m
 *
 * @param preference The preference to add.
 * @return Whether the preference is now in this group.
 */
public boolean addPreference(Preference preference) {
    if (mPreferenceList.contains(preference)) {
        // Exists
        return true;
    }

    if (preference.getOrder() == DEFAULT_ORDER) {
        if (mOrderingAsAdded) {
            preference.setOrder(mCurrentPreferenceOrder++);
        }

        if (preference instanceof PreferenceGroup) {
            // TODO: fix (method is called tail recursively when inflating,
            // so we won't end up properly passing this flag down to children
            ((PreferenceGroup) preference).setOrderingAsAdded(mOrderingAsAdded);
        }
    }

    int insertionIndex = Collections.binarySearch(mPreferenceList, preference);
    if (insertionIndex < 0) {
        insertionIndex = insertionIndex * -1 - 1;
    }

    if (!onPrepareAddPreference(preference)) {
        return false;
    }

    synchronized (this) {
        mPreferenceList.add(insertionIndex, preference);
    }

    preference.onAttachedToHierarchy(getPreferenceManager());

    if (mAttachedToHierarchy) {
        preference.onAttached();
    }

    notifyHierarchyChanged();

    return true;
}

From source file:TweetAttributes.java

public double getJaccardDistance(final TweetAttributes tweet1, final TweetAttributes tweet2) {
    double jaccardDistance = 0.0;
    String[] tweetText1 = tweet1.getText().split("\\s");
    String[] tweetText2 = tweet2.getText().split("\\s");

    Set<String> ts1 = new HashSet<>();
    Set<String> ts2 = new HashSet<>();

    for (String wordInTweet1 : tweetText1) {
        ts1.add(wordInTweet1);//from  ww  w . j  a  v a  2  s.  co  m
    }

    for (String wordInTweet2 : tweetText2) {
        ts2.add(wordInTweet2);
    }

    List<String> t1 = new ArrayList<>();
    t1.addAll(ts1);
    List<String> t2 = new ArrayList<>();
    t2.addAll(ts2);

    Collections.sort(t1);
    int intersect = 0;
    for (String s : t2) {
        if (Collections.binarySearch(t1, s) >= 0) {
            intersect++;
        }
    }
    int totalSize = t1.size() + t2.size();
    int union = totalSize - intersect;
    jaccardDistance = 1 - ((double) intersect / union);
    return jaccardDistance;
}

From source file:org.drugis.common.beans.FilteredObservableList.java

private void elementChanged(final int elm) {
    final int idx = Collections.binarySearch(d_indices, elm);
    if (idx >= 0) {
        if (d_filter.evaluate(d_inner.get(elm))) {
            fireContentsChanged(idx, idx);
        } else {/* www.ja v a  2 s. co m*/
            d_indices.remove(idx);
            fireIntervalRemoved(idx, idx);
        }
    } else {
        if (d_filter.evaluate(d_inner.get(elm))) {
            d_indices.add(-(idx + 1), elm);
            fireIntervalAdded(-(idx + 1), -(idx + 1));
        } else {
            // no change
        }
    }
}

From source file:android.support.v7.preference.PreferenceGroup.java

/**
 * Adds a {@link Preference} at the correct position based on the
 * preference's order.//w  w  w.  j  av  a 2 s .  c  o  m
 *
 * @param preference The preference to add.
 * @return Whether the preference is now in this group.
 */
public boolean addPreference(Preference preference) {
    if (mPreferenceList.contains(preference)) {
        // Exists
        return true;
    }

    if (preference.getOrder() == DEFAULT_ORDER) {
        if (mOrderingAsAdded) {
            preference.setOrder(mCurrentPreferenceOrder++);
        }

        if (preference instanceof PreferenceGroup) {
            // TODO: fix (method is called tail recursively when inflating,
            // so we won't end up properly passing this flag down to children
            ((PreferenceGroup) preference).setOrderingAsAdded(mOrderingAsAdded);
        }
    }

    int insertionIndex = Collections.binarySearch(mPreferenceList, preference);
    if (insertionIndex < 0) {
        insertionIndex = insertionIndex * -1 - 1;
    }

    if (!onPrepareAddPreference(preference)) {
        return false;
    }

    synchronized (this) {
        mPreferenceList.add(insertionIndex, preference);
    }

    final PreferenceManager preferenceManager = getPreferenceManager();
    final String key = preference.getKey();
    final long id;
    if (key != null && mIdRecycleCache.containsKey(key)) {
        id = mIdRecycleCache.get(key);
        mIdRecycleCache.remove(key);
    } else {
        id = preferenceManager.getNextId();
    }
    preference.onAttachedToHierarchy(preferenceManager, id);

    if (mAttachedToHierarchy) {
        preference.onAttached();
    }

    notifyHierarchyChanged();

    return true;
}

From source file:ORG.oclc.os.SRW.SRWFileSystemDatabase.java

@Override
public QueryResult getQueryResult(String queryStr, SearchRetrieveRequestType request) {
    BasicQueryResult result = new BasicQueryResult();
    CQLNode query;/*from   w  w w . j  a  v  a2s .c o m*/
    try {
        query = parser.parse(queryStr);
    } catch (CQLParseException e) {
        result.addDiagnostic(SRWDiagnostic.QuerySyntaxError, queryStr);
        return result;
    } catch (IOException e) {
        result.addDiagnostic(SRWDiagnostic.QuerySyntaxError, queryStr);
        return result;
    }
    if (!(query instanceof CQLTermNode)) {
        result.addDiagnostic(SRWDiagnostic.UnsupportedBooleanOperator, null);
    }
    CQLTermNode term = (CQLTermNode) query;
    String index;
    index = term.getIndex();
    if (index.equals("oai.identifier") || index.equals("identifier")) {
        int filenameOffset = Collections.binarySearch(filenames, term.getTerm());
        if (filenameOffset >= 0) {
            result.setNumberOfRecords(1);
            try {
                byte[] b;
                InputStream recStream = Utilities.openInputStream(filenames.get(filenameOffset), dbHome, null);
                BufferedReader br = new BufferedReader(new InputStreamReader(recStream, "UTF-8"));
                String line;
                StringBuilder rec, recs[] = new StringBuilder[1];
                rec = recs[0] = new StringBuilder();
                while ((line = br.readLine()) != null)
                    rec.append(line);
                result.setRecords(recs);
            } catch (IOException ex) {
                log.error(ex, ex);
                result.addDiagnostic(SRWDiagnostic.GeneralSystemError, ex.getMessage());
            }
        }
    } else {
        result.addDiagnostic(SRWDiagnostic.UnsupportedIndex, index);
        return result;
    }
    result.setQuery(queryStr);

    return result;
}

From source file:edu.ku.brc.af.ui.db.PropertiesPickListAdapter.java

public PickListItemIFace addItem(final String title, final String value) {
    // this should never happen!
    if (pickList.getReadOnly()) {
        throw new RuntimeException("Trying to add an item to a readonly picklist [" + pickList.getName() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
    }/*from   www.j  a va 2s .  c  o m*/

    int sizeLimit = 50; // arbitrary size could be a pref (XXX PREF)
    Integer sizeLimitInt = pickList.getSizeLimit();
    if (sizeLimitInt != null) {
        sizeLimit = sizeLimitInt.intValue();
    }

    searchablePLI.setTitle(title);
    int index = Collections.binarySearch(items, searchablePLI);
    if (index < 0) {
        // find oldest item and remove it
        if (items.size() >= sizeLimit) {
            PickListItemIFace oldest = null;
            for (PickListItemIFace pli : items) {
                if (oldest == null
                        || pli.getTimestampCreated().getTime() < oldest.getTimestampCreated().getTime()) {
                    oldest = pli;
                }
            }
            items.remove(oldest);
            pickList.removeItem(oldest);
        }

        PickListItemIFace item = PickListDBAdapterFactory.getInstance().createPickListItem();
        item.setTitle(title);
        item.setValue(value);
        items.add(item);

        if (pickList != null) {
            pickList.addItem(item);
            item.setPickList(pickList);
            pickList.reorder();
        }
        Collections.sort(items);

        final int newItemInx = items.indexOf(item);

        if (doAutoSaveOnAdd) {
            save();
        }

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                for (ChangeListener cl : changeListeners) {
                    cl.stateChanged(new ChangeEvent(PropertiesPickListAdapter.this));
                }
                PropertiesPickListAdapter.this.comboBox.getComboBox().setSelectedIndex(newItemInx);
            }
        });

        return item;

    }
    // else
    return items.elementAt(index);
}

From source file:org.jfree.data.DefaultKeyedValues2D.java

/**
 * Returns the row index for a given key.
 *
 * @param key  the key (<code>null</code> not permitted).
 *
 * @return The row index./*from w  w w  .  ja v a2s  . com*/
 * 
 * @see #getRowKey(int)
 * @see #getColumnIndex(Comparable)
 */
public int getRowIndex(Comparable key) {
    if (key == null) {
        throw new IllegalArgumentException("Null 'key' argument.");
    }
    if (this.sortRowKeys) {
        return Collections.binarySearch(this.rowKeys, key);
    } else {
        return this.rowKeys.indexOf(key);
    }
}

From source file:org.hyperic.hq.plugin.cloudfoundry.inventory.CloudFoundryResourceManager.java

public void syncServices(List<ServiceResource> cloudResources) throws Exception {

    if (cloudResources == null) {
        return;//from  www.j  av a 2 s.co m
    }

    int numResourcesDeleted = 0;

    try {
        Resource cloudfoundry = getCloudFoundryServer(this.props);

        if (cloudfoundry == null) {
            if (_log.isDebugEnabled()) {
                _log.debug("Could not find a " + PROTOTYPE_CLOUD_FOUNDRY
                        + " server with the specified properties.");
            }
            return;
        }

        List<String> resources = new ArrayList();
        for (ServiceResource s : cloudResources) {
            String sname = getResourceName(s);
            if (sname != null) {
                resources.add(sname);
                if (_log.isDebugEnabled()) {
                    _log.debug(PROTOTYPE_CLOUD_FOUNDRY + " resource {" + "name=" + sname + "}");
                }
            }
        }

        Collections.sort(resources);
        for (Resource service : cloudfoundry.getResource()) {
            String sname = getResourceName(service.getResourceConfig());
            if (sname != null) {
                if (Collections.binarySearch(resources, sname) < 0) {
                    commandsClient.deleteResource(service);
                    if (_log.isDebugEnabled()) {
                        _log.debug(PROTOTYPE_CLOUD_FOUNDRY + " resource deleted {" + "Hyperic name="
                                + service.getName() + ", Cloud Foundry name=" + sname + "}");
                    }
                    numResourcesDeleted++;
                    // TODO: Create event log when resources are deleted
                }
            }
        }
    } catch (Exception e) {
        // TODO: log here?
        throw e;
    } finally {
        if (numResourcesDeleted > 0) {
            _log.info(numResourcesDeleted + " Cloud Foundry resources deleted");
        }
    }
}

From source file:org.jfree.data.DefaultKeyedValues2D.java

/**
 * Returns the row index for a given key.
 *
 * @param key  the key (<code>null</code> not permitted).
 *
 * @return The row index./*from   w  w  w  .  j a va2 s  .  c  om*/
 *
 * @see #getRowKey(int)
 * @see #getColumnIndex(Comparable)
 */
@Override
public int getRowIndex(Comparable key) {
    ParamChecks.nullNotPermitted(key, "key");
    if (this.sortRowKeys) {
        return Collections.binarySearch(this.rowKeys, key);
    } else {
        return this.rowKeys.indexOf(key);
    }
}

From source file:au.org.ala.sds.model.SensitiveTaxonStore.java

public SensitiveTaxon findByExactMatch(String name) {
    // Do binary search
    int idx = Collections.binarySearch(taxonList,
            new SensitiveTaxon(name, StringUtils.contains(name, ' ') ? RankType.SPECIES : RankType.GENUS));
    if (idx >= 0 && taxonList.get(idx).getName().equalsIgnoreCase(name)) {
        return taxonList.get(idx);
    } else {//from   ww w.j a  va2 s .  co m
        return null;
    }
}