List of usage examples for java.util Collections binarySearch
@SuppressWarnings("unchecked") public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
From source file:com.pinterest.deployservice.buildtags.BuildTagsManagerImpl.java
public TagBean getEffectiveBuildTag(List<BuildTagBean> tags, BuildBean build) throws Exception { //This is the current matching algorithm, it is a naive algorithm. //We have a list of tags sorted by the commit_date ascending. We have a specific commit. The matching //works as following: // 1. Binary search finding out the position i of build in the tags list where list[i-1]<=build.commit<list[i]. // This means all i-1 tags were created before (or equal to commit). // 2. Start from i-1 to 0. Getting the first tag if it has the same git,repo,branch of the build. Then it should // be the one applied. If there is no such i or 0, no tag can be applied. //Create a dummy so that we can call Collections.binarysearch BuildTagBean dummy = new BuildTagBean(build, null); LOG.debug("Search build {} in {} tags", build.getBuild_id(), tags.size()); int insert = Collections.binarySearch(tags, dummy, new Comparator<BuildTagBean>() { @Override//from w w w . jav a 2 s .c o m public int compare(BuildTagBean o1, BuildTagBean o2) { return o1.getBuild().getCommit_date().compareTo(o2.getBuild().getCommit_date()); } }); LOG.debug("Binary search returns {}", insert); // insert will be the (-(insertion point)-1) if not found. Insertion point is the index of the first element that is greater or .size() if all // elements is smaller. This sounds a bit weird. It is basically to ensure negative return when not finding the key. // https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#binarySearch-java.util.List-T-java.util.Comparator- // https://stackoverflow.com/questions/31104031/what-is-the-reasoning-behind-java-util-collections-binarysearch-return-value-wh int idx = insert < 0 ? -1 * (insert + 1) - 1 : insert; //This is our search start TagBean ret = null; for (int i = idx; i >= 0; i--) { BuildBean tagBuild = tags.get(i).getBuild(); if (tagBuild.getScm_commit().equals(build.getScm_commit())) { //Tag is on the exact commit LOG.debug("Found tag on the exact commit {}", tags.get(i).getTag().getValue(), tagBuild.getScm_commit()); ret = tags.get(i).getTag(); break; } else if (tagBuild.getScm().equals(build.getScm()) && tagBuild.getScm_branch().equals(build.getScm_branch())) { ret = tags.get(i).getTag(); break; } } return ret; }
From source file:net.testdriven.psiprobe.beans.LogResolverBean.java
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)); }//ww w . ja v a 2s . com } } return sources; }
From source file:edu.scripps.fl.collections.FuzzyMap.java
@Override @SuppressWarnings("unchecked") public boolean containsKey(Object key) { int idx = Collections.binarySearch((List) list, key, comparator); if (idx > 0) return true; else if (idx == 0) return list.size() > 0 && list.get(0).getKey().equals(key) ? true : false; else/*from ww w . j a va 2 s .c o m*/ return false; }
From source file:org.jets3t.apps.cockpitlite.CLObjectTableModel.java
public void removeObject(S3Object object) { sanitizeObjectKey(object);//from ww w . j a va 2 s . c o m int row = Collections.binarySearch(objectList, object, new Comparator() { public int compare(Object o1, Object o2) { return ((S3Object) o1).getKey().compareToIgnoreCase(((S3Object) o2).getKey()); } }); if (row >= 0) { this.removeRow(row); objectList.remove(row); } }
From source file:org.wso2.carbon.humantask.core.engine.util.OperationAuthorizationUtil.java
private static boolean isExcludedEntity(TaskDAO task, OrganizationalEntityDAO validatee, PeopleQueryEvaluator pqe) {// ww w. j a v a 2 s . co m GenericHumanRoleDAO excludedOwners = task .getGenericHumanRole(GenericHumanRoleDAO.GenericHumanRoleType.EXCLUDED_OWNERS); if (excludedOwners != null) { for (OrganizationalEntityDAO entityForRole : getGroupOrganizationalEntities(excludedOwners)) { if (OrganizationalEntityDAO.OrganizationalEntityType.GROUP .equals(entityForRole.getOrgEntityType())) { String roleName = entityForRole.getName(); List<String> userListForRole = pqe.getUserNameListForRole(roleName); if (userListForRole.contains(validatee.getName())) { log.error("User " + validatee.getName() + " is in EXCLUDED_OWNERS role"); return true; } } } List<OrganizationalEntityDAO> orgEntities = getUserOrganizationalEntities(excludedOwners); Collections.sort(orgEntities, PeopleQueryComparators.peopleNameComparator()); if (Collections.binarySearch(orgEntities, validatee, PeopleQueryComparators.peopleNameComparator()) >= 0) { log.error("User " + validatee.getName() + " is in EXCLUDED_OWNERS role"); return true; } } return false; }
From source file:org.b3log.symphony.service.ManQueryService.java
/** * Gets manuals by the specified command prefix. * * @param cmdPrefix the specified comman prefix * @return a list of manuals, for example, <pre> * [//from w ww . j a v a 2 s.co m * { * "manCmd": "find", * "manHTML": "...." * }, .... * ] * </pre>, returns an empty list if not found */ public List<JSONObject> getMansByCmdPrefix(final String cmdPrefix) { final JSONObject toSearch = new JSONObject(); toSearch.put(Common.MAN_CMD, cmdPrefix); final int index = Collections.binarySearch(CMD_MANS, toSearch, (o1, o2) -> { String c1 = o1.optString(Common.MAN_CMD); final String c2 = o2.optString(Common.MAN_CMD); if (c1.length() < c2.length()) { return c1.compareToIgnoreCase(c2); } c1 = c1.substring(0, c2.length()); return c1.compareToIgnoreCase(c2); }); final List<JSONObject> ret = new ArrayList<>(); if (index < 0) { return ret; } int start = index; int end = index; while (start > -1 && CMD_MANS.get(start).optString(Common.MAN_CMD).startsWith(cmdPrefix.toLowerCase())) { start--; } start++; final int WINDOW_SIZE = 8; if (start < index - WINDOW_SIZE) { end = start + WINDOW_SIZE; } else { while (end < CMD_MANS.size() && end < index + 5 && CMD_MANS.get(end).optString(Common.MAN_CMD).startsWith(cmdPrefix.toLowerCase())) { end++; if (end >= start + WINDOW_SIZE) { break; } } } return CMD_MANS.subList(start, end); }
From source file:mondrian.util.UtilCompatibleJdk14.java
public <T extends Comparable<T>> int binarySearch(T[] ts, int start, int end, T t) { return Collections.binarySearch(Arrays.asList(ts).subList(start, end), t, RolapUtil.ROLAP_COMPARATOR); }
From source file:com.googlecode.psiprobe.beans.LogResolverBean.java
public List getLogSources() { List sources = new LinkedList(); List allAppenders = getAllLogDestinations(); if (allAppenders != null) { LogComparator cmp = new LogSourceComparator(); Collections.sort(allAppenders, cmp); for (int i = 0; i < allAppenders.size(); i++) { LogDestination dest = (LogDestination) allAppenders.get(i); if (Collections.binarySearch(sources, dest, cmp) < 0) { sources.add(new DisconnectedLogDestination(dest)); }/* ww w.j a va 2 s . c o m*/ } } return sources; }
From source file:org.icefaces.application.showcase.view.bean.examples.component.selectInputText.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. *///from w w w. ja va 2 s . com 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 { SelectItem searchItem = new SelectItem("", searchWord); init(); int insert = Collections.binarySearch(cityDictionary, 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 != cityDictionary.size() && LABEL_COMPARATOR.compare(searchItem, cityDictionary.get(insert)) == 0) { while (insert > 0 && LABEL_COMPARATOR.compare(searchItem, cityDictionary.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) >= cityDictionary.size() || i >= maxMatches) { break; } matchList.add(cityDictionary.get(insert + i)); } } catch (Throwable e) { log.error(MessageBundleLoader.getMessage("bean.selectInputText.error.findingMatches"), e); } // assign new matchList return matchList; }
From source file:com.android.volley.toolbox.ByteArrayPool.java
/** * Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted * size.//from w w w . j a va 2 s .c om * * @param buf the buffer to return to the pool. */ public synchronized void returnBuf(byte[] buf) { if (buf == null || buf.length > mSizeLimit) { return; } mBuffersByLastUse.add(buf); int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR); if (pos < 0) { pos = -pos - 1; } mBuffersBySize.add(pos, buf); mCurrentSize += buf.length; trim(); }