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:com.aqnote.app.wifianalyzer.wifi.band.Country.java

public Locale getCountry(@NonNull String countryCode) {
    Locale country = new Locale("", countryCode);
    int index = Collections.binarySearch(countries, country, new LocaleCountryComparator());
    if (index < 0) {
        return country;
    }//from  ww w . j  av a 2 s . c  o m
    return countries.get(index);
}

From source file:fr.syncarnet.tasks.TaskList.java

/**
 * Inserts a new task at the adequate position based on its due date and priority.
 *///  w  w  w.j  a  v  a2s .c o m
@Override
public boolean add(Task task) {
    Task.CompareWithDueAndPriority comparator = new Task.CompareWithDueAndPriority();
    int i = Collections.binarySearch(this, task, comparator);
    i = (i < 0) ? (-i) - 1 : ++i;
    super.add(i, task);
    if (!projects.contains(task.getProject()) && task.getProject() != null) {
        projects.add(task.getProject());
    }
    return true;
}

From source file:com.spotify.hdfs2cass.CassandraPartitioner.java

@Override
public int getPartition(Text key, Text value, int numReducers) {
    final int partition;

    final BigIntegerToken token = partitioner.getToken(ByteBuffer.wrap(key.getBytes()));

    final int index = Collections.binarySearch(tokenNodes, new TokenNode(token), SEARCH_COMPARATOR);
    if (index >= 0) {
        final int multiple = numReducers / tokenNodes.size();
        partition = index + (multiple * RANDOM.nextInt(multiple));
    } else {/*from   ww  w  .j  a v  a2s  . c  om*/
        throw new RuntimeException("Failed to find a node for token " + token);
    }

    return partition;
}

From source file:org.jets3t.apps.cockpitlite.CLObjectTableModel.java

public int addObject(S3Object object) {
    sanitizeObjectKey(object);//from w  w  w  . j  a  v a  2s .com

    int insertRow = Collections.binarySearch(objectList, object, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((S3Object) o1).getKey().compareToIgnoreCase(((S3Object) o2).getKey());
        }
    });

    String aclStatus = null;
    if (insertRow >= 0) {
        // Retain the object's ACL status if it's available.
        aclStatus = (String) this.getValueAt(insertRow, 3);

        // We already have an item with this key, replace it.
        objectList.remove(insertRow);
        this.removeRow(insertRow);
    } else {
        insertRow = (-insertRow) - 1;
    }

    if (object.getAcl() != null || aclStatus == null) {
        aclStatus = CockpitLite.getAclDescription(object.getAcl());
    }

    // New object to insert.
    objectList.add(insertRow, object);
    this.insertRow(insertRow, new Object[] { object.getKey(), new Long(object.getContentLength()),
            object.getLastModifiedDate(), aclStatus });

    return insertRow;
}

From source file:com.joconner.g11n.charprop.service.BlocksService.java

public Block getBlockFor(int ch) {
    Block b = noBlock;/*from  w w w. j av a  2 s  .  c o  m*/
    Block chBlock = new Block(null, ch, ch);
    int index = Collections.binarySearch(blocks, chBlock, (Block o1, Block o2) -> {
        int o1b = o1.getBegin();
        int o1e = o1.getEnd();
        int o2b = o2.getBegin();
        int o2e = o2.getEnd();

        if (o1b < o2b && o1e < o2e) {
            return -1;
        } else if (o1b > o2b && o1e > o2e) {
            return 1;
        } else {
            return 0;
        }
    });

    if (index >= 0 && index < blocks.size()) {
        b = blocks.get(index);
    }
    return b;
}

From source file:com.prime.app.agvirtual.web.jsf.component.selectinputtext.UfDictionary.java

/**
 * Generates a short list of cities that match the given searchWord. The
 * length of the list is specified by the maxMatches attribute.
 * /*from   ww  w .  j ava  2s .c  o  m*/
 * @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.
 */
public static 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 {
        SelectItem searchItem = new SelectItem("", searchWord);
        int insert = Collections.binarySearch(ufDictionary, searchItem, LABEL_COMPARATOR);

        // less then zero if we have a partial match
        if (insert < 0) {
            insert = Math.abs(insert) - 1;
        } else {
            // If there are duplicates in a list, ensure we start from the
            // first one
            if (insert != ufDictionary.size()
                    && LABEL_COMPARATOR.compare(searchItem, ufDictionary.get(insert)) == 0) {
                while (insert > 0 && LABEL_COMPARATOR.compare(searchItem, ufDictionary.get(insert - 1)) == 0) {
                    insert = 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) >= ufDictionary.size() || i >= maxMatches) {
                break;
            }
            matchList.add(ufDictionary.get(insert + i));
        }
    } catch (Throwable e) {
        log.error(e.getMessage());

    }
    // assign new matchList
    return matchList;
}

From source file:org.antbear.jee.wicket.guestbook.model.Guestbook.java

public void add(Entry entry) {
    if (entry == null)
        throw new NullPointerException("entry must not be null");

    int pos = Collections.binarySearch(entries, entry, new Entry.Comparator());
    if (pos < 0) {
        pos = -(pos + 1);//from  w  w  w.j  av  a2s .  co  m
    }
    entries.add(pos, entry);
}

From source file:com.epam.dlab.core.aggregate.DataAggregator.java

/**
 * Appends the report line to the list and returns it.
 *
 * @param row the line of report./* ww  w .j av  a2s  .  c  o m*/
 * @return Instance of the aggregated report line.
 */
public ReportLine append(ReportLine row) {
    synchronized (this) {
        String usageInterval = truncDate(row.getUsageDate());
        row.setUsageDate(usageInterval);
        int index = Collections.binarySearch(reportLines, row, aggComparator);
        if (index < 0) {
            index = -index;
            if (index > reportLines.size()) {
                reportLines.add(row);
            } else {
                reportLines.add(index - 1, row);
            }
        } else {
            ReportLine found = reportLines.get(index);
            found.setUsage(found.getUsage() + row.getUsage());
            found.setCost(found.getCost() + row.getCost());
            return found;
        }
    }

    return row;
}

From source file:org.wso2.carbon.humantask.core.engine.util.OperationAuthorizationUtil.java

/**
 * @param task             : The task against which the user being validated.
 * @param validatee        : The OrganizationalEntityDAO being validated.
 * @param allowedRoleTypes : The allowed role types for the validatee object.
 * @param pqe              : PeopleQueryEvaluator for people queries.
 * @return : true if the user is in the specified roles for the given task. false otherwise.
 *///www  .ja  v  a 2 s .co m
public static boolean authoriseUser(TaskDAO task, OrganizationalEntityDAO validatee,
        List<GenericHumanRoleDAO.GenericHumanRoleType> allowedRoleTypes, PeopleQueryEvaluator pqe) {
    List<GenericHumanRoleDAO> humanRolesInTask = task.getHumanRoles();

    if (isExcludedEntity(task, validatee, pqe)) {
        return false;
    }

    for (GenericHumanRoleDAO role : humanRolesInTask) {
        if (allowedRoleTypes.contains(role.getType())) {

            // check for groups
            for (OrganizationalEntityDAO entityForRole : getGroupOrganizationalEntities(role)) {
                if (OrganizationalEntityDAO.OrganizationalEntityType.GROUP
                        .equals(entityForRole.getOrgEntityType())) {
                    String roleName = entityForRole.getName();
                    List<String> userListForRole = pqe.getUserNameListForRole(roleName);
                    if (userListForRole.contains(validatee.getName())) {
                        return true;
                    }
                }
            }

            //check for users
            //TODO validate user existance in the user store.
            List<OrganizationalEntityDAO> orgEntities = getUserOrganizationalEntities(role);
            Collections.sort(orgEntities, PeopleQueryComparators.peopleNameComparator());
            if (Collections.binarySearch(orgEntities, validatee,
                    PeopleQueryComparators.peopleNameComparator()) >= 0) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.jets3t.apps.cockpitlite.CLObjectTableModel.java

public int updateObjectAclStatus(S3Object objectWithAcl, String aclStatus) {
    sanitizeObjectKey(objectWithAcl);// w w w .j  a v  a 2s  .  co m

    int updateRow = Collections.binarySearch(objectList, objectWithAcl, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((S3Object) o1).getKey().compareToIgnoreCase(((S3Object) o2).getKey());
        }
    });
    if (updateRow >= 0) {
        this.setValueAt(aclStatus, updateRow, 3);
    } else {
        // Object isn't in table!
        log.warn("Cannot find object named '" + objectWithAcl.getKey() + "' in objects table");
    }
    return updateRow;
}