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:org.jaffa.qm.util.PropertyFilter.java

private void calculateFilter(Class clazz, String[] rules) throws IntrospectionException {
    m_rules = rules != null && rules.length > 0 ? rules : new String[] { "*" };
    List<String> filteredFields = new ArrayList<String>();
    List<String> relToCheck = new LinkedList<String>();

    // Convert rules to RegEx and cache...
    m_filterTypes = new boolean[m_rules.length + 1];
    m_filterPatterns = new Pattern[m_rules.length + 1];
    for (int i = 0; i < m_rules.length; i++) {
        String filter = m_rules[i];
        Pattern p = null;/*  ww w  .j ava  2 s  .  c  om*/
        boolean exclude = false;
        if (filter != null && filter.length() > 0) {
            exclude = filter.charAt(0) == '-';
            if (exclude || filter.charAt(0) == '+')
                filter = filter.substring(1);
            /* Convert filter to a regex. Rules are...
             *  . => \.
             *  ** => [\w\.]+
             *  * => [\w]+
             */
            filter = StringHelper.replace(filter, ".", "\\.");
            filter = StringHelper.replace(filter, "**", "[\\w\\.]+");
            filter = StringHelper.replace(filter, "*", "[\\w]+");
            if (log.isDebugEnabled())
                log.debug("Converted filter '" + m_rules[i] + "' to pattern '" + filter + "'");
            p = Pattern.compile(filter);
        }
        m_filterTypes[i] = exclude;
        m_filterPatterns[i] = p;
    }

    // Now build list of acceptable fields
    List<String> allFields = getFieldList(clazz);
    if (allFields != null) {
        for (String field : allFields) {
            boolean foreign = field.startsWith("+");
            boolean related = field.startsWith("*");
            if (foreign || related)
                field = field.substring(1);
            Boolean include = includeField(field);
            if (include != null && include) {
                filteredFields.add(field);
                if (related)
                    relToCheck.add(field);
            }
        }
        Collections.sort(filteredFields);
    }

    // Removed related reference if there are no related fields
    for (String field : relToCheck) {
        if (log.isDebugEnabled())
            log.debug("Check related object " + field);
        if (!areSubFieldsIncluded(filteredFields, field)) {
            int i = Collections.binarySearch(filteredFields, field);
            if (i >= 0) {
                filteredFields.remove(i);
                if (log.isDebugEnabled())
                    log.debug("Removed related object " + field);
            }
        }
    }

    // Now make sure based on all the filtering, that all parent object referenced
    // are in place. You can't have x.y.z without first having x.y and therefore x
    for (int cursor = 0; cursor < filteredFields.size(); ++cursor) {
        // perform the check recursively since the addition of 'x.y.z' might also require the insertion of 'x.y' and so on..
        String field = (String) filteredFields.get(cursor);
        while (true) {
            int pos = field.lastIndexOf('.');
            if (pos > 0) {
                field = field.substring(0, pos);
                int i = Collections.binarySearch(filteredFields, field);
                if (i < 0) {
                    // Determine the insertion point. Note: the value of i is (-(insertion point) - 1)
                    i = -(i + 1);
                    filteredFields.add(i, field);
                    if (log.isDebugEnabled())
                        log.debug("Added missing parent object " + field);
                    if (i <= cursor)
                        ++cursor;
                }
            } else {
                break;
            }
        }
    }

    m_filteredFields = filteredFields;
}

From source file:org.apache.cassandra.locator.TokenMetadata.java

public static int firstTokenIndex(final ArrayList ring, Token start, boolean insertMin) {
    assert ring.size() > 0;
    // insert the minimum token (at index == -1) if we were asked to include it and it isn't a member of the ring
    int i = Collections.binarySearch(ring, start);
    if (i < 0) {
        i = (i + 1) * (-1);/*from  w w w .  ja va  2s  .c  o m*/
        if (i >= ring.size())
            i = insertMin ? -1 : 0;
    }
    return i;
}

From source file:ngo.music.soundcloudplayer.controller.SongController.java

/**
 * search the Id of song in a list/* w w  w. j av  a 2  s .  c  o m*/
 * 
 */
private int searchId(ArrayList<Integer> songidList, int songID) {

    return Collections.binarySearch(songidList, songID);

}

From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.db.impl.TeradataExtractServiceImpl.java

private void setDependenciesTable(List<HashMap<String, String>> columnRel) {
    for (HashMap<String, String> cols : columnRel) {
        // ???//from   ww  w  . j a v a 2s  .  c  o  m
        String srcObj = cols.get("Src_Obj").toUpperCase();
        String tgtObj = cols.get("Tgt_Obj").toUpperCase();
        // SRC,TGT?,?
        // ?:3,?schema.table.column?;???
        String[] tgtObjs = tgtObj.split("\\.");

        // ?
        NamedColumnSet simTgtView = new View();
        simTgtView.setName(tgtObjs[1]);
        List<NamedColumnSet> columnSets = cntSchema.getColumnSets();
        int index = Collections.binarySearch(columnSets, simTgtView);
        if (index < 0) {
            continue;
        }
        // index
        // >=0,?(??,??...??!?...??....)
        // ?,?,??,Map,?,???
        View tgtView = (View) columnSets.get(index);
        // ???
        NamedColumnSetType srcType = getNamedColumnSetType(srcObj);

        tgtView.addReferenceSchTable(srcObj, srcType);

    }
}

From source file:ru.moscow.tuzlukov.sergey.weatherlog.MainActivity.java

private void processValues(boolean useCached) {
    if (!(currentIsGained && historyIsGained))
        return;// w w  w.ja  v a  2s . c  o  m
    if (temperatureMap.size() >= 2 && !useCached)
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(
                    openFileOutput(CACHED_MAP_FILE, MODE_PRIVATE));
            outputStream.writeObject(temperatureMap);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    llLoader.setVisibility(View.GONE);
    ptrLayout.setRefreshComplete();

    if (temperatureMap.size() < 2) {
        Toast.makeText(MainActivity.this, getString(R.string.no_data_error_message), Toast.LENGTH_SHORT).show();
        cachingTimestamp = 0;
        return;
    }

    // remove all redundant values, that are older than 24 hours ago,
    // and calculate temperature at accurate 24-hours-back limit (first value in timeline)
    List<Long> sortedTimeList = new ArrayList<>(temperatureMap.keySet());
    int indexOfMinus24h = Collections.binarySearch(sortedTimeList, currentTimeMinus24h);
    double temperatureAtMinus24h;
    if (indexOfMinus24h < 0) {
        indexOfMinus24h = -indexOfMinus24h - 1;
        temperatureAtMinus24h = temperatureByTime(sortedTimeList, indexOfMinus24h, currentTimeMinus24h);
    } else {
        temperatureAtMinus24h = temperatureMap.get(currentTimeMinus24h);
    }
    for (int n = 0; n < indexOfMinus24h; n++)
        temperatureMap.remove(sortedTimeList.get(n));
    temperatureMap.put(currentTimeMinus24h, temperatureAtMinus24h);

    List<Double> sortedTempList = new ArrayList<>(temperatureMap.values());
    Collections.sort(sortedTempList);
    // statistical indicators
    double average = averageInList(sortedTempList), median = medianInList(sortedTempList),
            span = spanInList(sortedTempList);

    // total time, at which temperature was below 0 and below +5, in intervals of previous 12 and 24 hours
    long totalTimeFirstLimit12h, totalTimeSecondLimit12h, totalTimeFirstLimit24h, totalTimeSecondLimit24h;
    totalTimeFirstLimit12h = calculateTotalTimeLessThan(temperatureLimit1, currentTimeMinus12h);
    totalTimeSecondLimit12h = calculateTotalTimeLessThan(temperatureLimit2, currentTimeMinus12h);
    totalTimeFirstLimit24h = calculateTotalTimeLessThan(temperatureLimit1, currentTimeMinus24h);
    totalTimeSecondLimit24h = calculateTotalTimeLessThan(temperatureLimit2, currentTimeMinus24h);

    // display calculated values on screen
    String format = "%.1f " + getString(R.string.hours_caption);
    tvTime1Limit1.setText(String.format(format, timeRangeApproxHours(totalTimeFirstLimit12h)));
    tvTime1Limit2.setText(String.format(format, timeRangeApproxHours(totalTimeSecondLimit12h)));
    tvTime2Limit1.setText(String.format(format, timeRangeApproxHours(totalTimeFirstLimit24h)));
    tvTime2Limit2.setText(String.format(format, timeRangeApproxHours(totalTimeSecondLimit24h)));
    tvDayTemperatureSpan.setText(String.format(getString(R.string.day_temperature_span_label), span));
    tvDayAverageTemperature.setText(String.format(getString(R.string.day_average_temperature_label), average));
    tvDayMedianTemperature.setText(String.format(getString(R.string.day_median_temperature_label), median));

    makePlot(sortedTempList.get(0), sortedTempList.get(sortedTempList.size() - 1));

    if (!useCached)
        cachingTimestamp = System.currentTimeMillis();
}

From source file:au.org.ala.biocache.dao.SearchDAOImpl.java

/**
 * (Endemic)//from ww  w . j  a  v a2 s .  c  om
 *
 * Returns a list of species that are only within a subQuery.
 *
 * The subQuery is a subset of parentQuery.
 */
public List<FieldResultDTO> getSubquerySpeciesOnly(SpatialSearchRequestParams subQuery,
        SpatialSearchRequestParams parentQuery) throws Exception {
    if (executor == null) {
        executor = Executors.newFixedThreadPool(maxMultiPartThreads);
    }
    // 1)get a list of species that are in the WKT
    logger.debug("Starting to get Endemic Species...");
    subQuery.setFacet(true);
    subQuery.setFacets(parentQuery.getFacets());
    List<FieldResultDTO> list1 = getValuesForFacet(subQuery);
    logger.debug("Retrieved species within area...(" + list1.size() + ")");

    int i = 0, localterms = 0;

    String facet = parentQuery.getFacets()[0];
    String[] originalFqs = parentQuery.getFq();
    List<Future<List<FieldResultDTO>>> threads = new ArrayList<Future<List<FieldResultDTO>>>();
    //batch up the rest of the world query so that we have fqs based on species we want to test for. This should improve the performance of the endemic services.
    while (i < list1.size()) {
        StringBuffer sb = new StringBuffer();
        while ((localterms == 0 || localterms % termQueryLimit != 0) && i < list1.size()) {
            if (localterms != 0)
                sb.append(" OR ");
            String value = list1.get(i).getFieldValue();
            if (facet.equals(NAMES_AND_LSID)) {
                if (value.startsWith("\"") && value.endsWith("\"")) {
                    value = value.substring(1, value.length() - 1);
                }
                value = "\"" + ClientUtils.escapeQueryChars(value) + "\"";
            } else {
                value = ClientUtils.escapeQueryChars(value);
            }
            sb.append(facet).append(":").append(value);
            i++;
            localterms++;
        }
        String newfq = sb.toString();
        if (localterms == 1)
            newfq = newfq + " OR " + newfq; //cater for the situation where there is only one term.  We don't want the term to be escaped again
        localterms = 0;
        SpatialSearchRequestParams srp = new SpatialSearchRequestParams();
        BeanUtils.copyProperties(parentQuery, srp);
        srp.setFq((String[]) ArrayUtils.add(originalFqs, newfq));
        int batch = i / termQueryLimit;
        EndemicCallable callable = new EndemicCallable(srp, batch, this);
        threads.add(executor.submit(callable));
    }

    Collections.sort(list1);
    for (Future<List<FieldResultDTO>> future : threads) {
        List<FieldResultDTO> list = future.get();
        if (list != null) {
            for (FieldResultDTO find : list) {
                int idx = Collections.binarySearch(list1, find);
                //remove if subquery count < parentquery count
                if (idx >= 0 && list1.get(idx).getCount() < find.getCount()) {
                    list1.remove(idx);
                }
            }
        }
    }
    logger.debug("Determined final endemic list (" + list1.size() + ")...");
    return list1;
}

From source file:org.jfree.data.xy.XYSeries.java

/**
 * Adds a data item to the series and, if requested, sends a
 * {@link SeriesChangeEvent} to all registered listeners.
 *
 * @param item  the (x, y) item (<code>null</code> not permitted).
 * @param notify  a flag that controls whether or not a
 *                {@link SeriesChangeEvent} is sent to all registered
 *                listeners.//  www  .  j  av  a2s  . c  o m
 */
public void add(XYDataItem item, boolean notify) {
    ParamChecks.nullNotPermitted(item, "item");
    item = (XYDataItem) item.clone();
    if (this.autoSort) {
        int index = Collections.binarySearch(this.data, item);
        if (index < 0) {
            this.data.add(-index - 1, item);
        } else {
            if (this.allowDuplicateXValues) {
                // need to make sure we are adding *after* any duplicates
                int size = this.data.size();
                while (index < size && item.compareTo(this.data.get(index)) == 0) {
                    index++;
                }
                if (index < this.data.size()) {
                    this.data.add(index, item);
                } else {
                    this.data.add(item);
                }
            } else {
                throw new SeriesException("X-value already exists.");
            }
        }
    } else {
        if (!this.allowDuplicateXValues) {
            // can't allow duplicate values, so we need to check whether
            // there is an item with the given x-value already
            int index = indexOf(item.getX());
            if (index >= 0) {
                throw new SeriesException("X-value already exists.");
            }
        }
        this.data.add(item);
    }
    updateBoundsForAddedItem(item);
    if (getItemCount() > this.maximumItemCount) {
        XYDataItem removed = (XYDataItem) this.data.remove(0);
        updateBoundsForRemovedItem(removed);
    }
    if (notify) {
        fireSeriesChanged();
    }
}

From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.db.impl.TeradataExtractServiceImpl.java

private NamedColumnSetType getNamedColumnSetType(String srcObj) {

    if (types.containsKey(srcObj)) {
        return types.get(srcObj);
    }//from w w w. j av a 2 s. c o m

    List<Schema> schemas = catalog.getSchemas();
    // ??schema
    List<Schema> schemaLists = new ArrayList<Schema>();
    schemaLists.addAll(schemas);
    schemaLists.addAll(schemaList);
    try {
        String[] srcSchemaTable = srcObj.split("\\.");
        for (Schema schema : schemaLists) {
            if (schema.getName().equals(srcSchemaTable[0])) {
                // ?SCHEMA
                List<NamedColumnSet> namedColumnSet = schema.getColumnSets();
                // 1.?
                NamedColumnSet srcTable = new Table();
                srcTable.setName(srcSchemaTable[1]);
                int index = Collections.binarySearch(namedColumnSet, srcTable);
                if (index > -1) {
                    types.put(srcObj, namedColumnSet.get(index).getType());
                    return types.get(srcObj);
                }
                break;
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn(e);
        }
    }
    // ?
    types.put(srcObj, NamedColumnSetType.TABLE);
    return NamedColumnSetType.TABLE;
}

From source file:com.wizecommerce.hecuba.hector.HectorBasedHecubaClientManager.java

protected void updateSecondaryIndexColumn(K key, String columnName, String columnValue, long timestamp,
        int ttl) {

    if (Collections.binarySearch(columnsToIndexOnColumnNameAndValue, columnName) >= 0) {

        // first retrieve the old value of this column to delete it from the secondary index.
        HColumn<String, String> oldColumn = getColumnFamily().querySingleColumn(key, columnName,
                StringSerializer.get());

        updateSecondaryIndexColumnFamily(key, columnName, columnValue, timestamp, ttl,
                oldColumn != null ? oldColumn.getValue() : "");
    }/*from  w  w  w  .  j  a va 2 s. co  m*/

}

From source file:android.support.v7.widget.AppCompatTextViewAutoSizeHelper.java

private int[] cleanupAutoSizePresetSizes(int[] presetValues) {
    final int presetValuesLength = presetValues.length;
    if (presetValuesLength == 0) {
        return presetValues;
    }/* w  w  w.  ja  va 2 s . c  o  m*/
    Arrays.sort(presetValues);

    final List<Integer> uniqueValidSizes = new ArrayList<>();
    for (int i = 0; i < presetValuesLength; i++) {
        final int currentPresetValue = presetValues[i];

        if (currentPresetValue > 0 && Collections.binarySearch(uniqueValidSizes, currentPresetValue) < 0) {
            uniqueValidSizes.add(currentPresetValue);
        }
    }

    if (presetValuesLength == uniqueValidSizes.size()) {
        return presetValues;
    } else {
        final int uniqueValidSizesLength = uniqueValidSizes.size();
        final int[] cleanedUpSizes = new int[uniqueValidSizesLength];
        for (int i = 0; i < uniqueValidSizesLength; i++) {
            cleanedUpSizes[i] = uniqueValidSizes.get(i);
        }
        return cleanedUpSizes;
    }
}