java.util.Collections.binarySearch()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.9k)|赞(0)|评价(0)|浏览(252)

本文整理了Java中java.util.Collections.binarySearch()方法的一些代码示例,展示了Collections.binarySearch()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collections.binarySearch()方法的具体详情如下:
包路径:java.util.Collections
类名称:Collections
方法名:binarySearch

Collections.binarySearch介绍

[英]Performs a binary search for the specified element in the specified sorted list. The list needs to be already sorted in natural sorting order. Searching in an unsorted array has an undefined result. It's also undefined which element is found if there are multiple occurrences of the same element.
[中]对指定排序列表中的指定元素执行二进制搜索。列表需要已经按自然排序顺序排序。在未排序的数组中搜索具有未定义的结果。如果同一元素多次出现,则未定义找到哪个元素。

代码示例

代码示例来源:origin: skylot/jadx

public ResourceEntry getByRef(int refId) {
  ResourceEntry key = new ResourceEntry(refId);
  int index = Collections.binarySearch(list, key, Comparator.comparingInt(ResourceEntry::getId));
  if (index < 0) {
    return null;
  }
  return list.get(index);
}

代码示例来源:origin: knowm/XChange

private void update(List<LimitOrder> asks, LimitOrder limitOrder) {
 int idx = Collections.binarySearch(asks, limitOrder);
 if (idx >= 0) {
  asks.remove(idx);
  asks.add(idx, limitOrder);
 } else {
  asks.add(-idx - 1, limitOrder);
 }
}

代码示例来源:origin: pmd/pmd

private int getIndexForDocumentOperation(final DocumentOperation documentOperation) {
  int potentialIndex = Collections.binarySearch(operations, documentOperation, COMPARATOR);
  if (potentialIndex < 0) {
    return ~potentialIndex;
  }
  final int lastIndex = operations.size() - 1;
  while (potentialIndex < lastIndex && areSiblingsEqual(potentialIndex)) {
    potentialIndex++;
  }
  return potentialIndex + 1;
}

代码示例来源:origin: apache/kylin

public void upsertAce(Permission permission, Sid sid) {
  Assert.notNull(sid, "Sid required");
  AceImpl ace = new AceImpl(sid, permission);
  synchronized (entries) {
    int p = Collections.binarySearch(entries, ace, AceImpl.SID_ORDER);
    if (p >= 0) {
      if (permission == null) // null permission means delete
        entries.remove(p);
      else
        entries.get(p).setPermission(permission);
    } else {
      if (permission != null) { // if not delete
        ace.init(this, entries.size());
        entries.add(-p - 1, ace);
      }
    }
  }
}

代码示例来源:origin: Codecademy/EventHub

public long findFirstEventIdOnDate(long eventIdForStartDate, int numDaysAfter) {
 int startDateOffset = Collections.binarySearch(earliestEventIds, eventIdForStartDate);
 if (startDateOffset < 0) {
  if (startDateOffset == -1) {
   startDateOffset = 0;
  } else {
   startDateOffset = -startDateOffset - 2;
  }
 }
 String dateOfEvent = dates.get(startDateOffset);
 String endDate = DATE_TIME_FORMATTER.print(
   DateTime.parse(dateOfEvent, DATE_TIME_FORMATTER).plusDays(numDaysAfter));
 int endDateOffset = Collections.binarySearch(dates, endDate);
 if (endDateOffset < 0) {
  endDateOffset = -endDateOffset - 1;
  if (endDateOffset >= earliestEventIds.size()) {
   return Long.MAX_VALUE;
  }
 }
 return earliestEventIds.get(endDateOffset);
}

代码示例来源:origin: thinkaurelius/titan

public EntryList getSubset(final SliceQuery otherQuery, final EntryList otherResult) {
  assert otherQuery.subsumes(this);
  int pos = Collections.binarySearch(otherResult, sliceStart);
  if (pos < 0) pos = -pos - 1;
  List<Entry> result = new ArrayList<Entry>();
  for (; pos < otherResult.size() && result.size() < getLimit(); pos++) {
    Entry e = otherResult.get(pos);
    if (e.getColumnAs(StaticBuffer.STATIC_FACTORY).compareTo(sliceEnd) < 0) result.add(e);
    else break;
  }
  return StaticArrayEntryList.of(result);
}

代码示例来源:origin: apache/hbase

CompactionDelPartitionId id = new CompactionDelPartitionId(null, partition.getStartKey());
CompactionDelPartition target = new CompactionDelPartition(id);
int start = Collections.binarySearch(delPartitions, target, comparator);
 if (start == delPartitions.size()) {
  if (Bytes.compareTo(partition.getEndKey(), delPartitions.get(start).getId().getStartKey()) < 0) {
   return result;
int end = Collections.binarySearch(delPartitions, target, comparator);
 } else {
  --end;
  if (Bytes.compareTo(partition.getStartKey(), delPartitions.get(end).getId().getEndKey()) > 0) {
   return result;
  result.addAll(delPartitions.get(i).getStoreFiles());

代码示例来源:origin: org.apache.hadoop/hadoop-hdfs

AclEntry defaultEntryKey = new AclEntry.Builder().setScope(DEFAULT)
 .setType(type).build();
int defaultEntryIndex = Collections.binarySearch(defaultEntries,
 defaultEntryKey, ACL_ENTRY_COMPARATOR);
if (defaultEntryIndex < 0) {
 AclEntry accessEntryKey = new AclEntry.Builder().setScope(ACCESS)
  .setType(type).build();
 int accessEntryIndex = Collections.binarySearch(accessEntries,
  accessEntryKey, ACL_ENTRY_COMPARATOR);
 if (accessEntryIndex >= 0) {
  copiedEntries.add(new AclEntry.Builder()
   .setScope(DEFAULT)
   .setType(type)
   .setPermission(accessEntries.get(accessEntryIndex).getPermission())
   .build());

代码示例来源:origin: pmd/pmd

public ClassNode defineClass(String className) {
  checkClassName(className);
  int index = Collections.binarySearch(classNodes, className, ClassNodeComparator.INSTANCE);
  ClassNode classNode;
  if (index >= 0) {
    classNode = classNodes.get(index);
  } else {
    classNode = new ClassNode(className);
    classNodes.add(-(index + 1), classNode);
  }
  return classNode;
}

代码示例来源:origin: oracle/opengrok

int index = Collections.binarySearch(outputScripts, script, new Comparator<Script>() {
  @Override
  public int compare(Script a, Script b) {
  this.outputScripts.add(Math.abs(index + 1), script);
} else {
  while (index < this.outputScripts.size()
      && this.outputScripts.get(index).getPriority() == script.getPriority()) {
    index++;
  this.outputScripts.add(index, script);

代码示例来源:origin: google/ExoPlayer

boolean inclusive,
 boolean stayInBounds) {
int index = Collections.binarySearch(list, value);
if (index < 0) {
 index = ~index;
} else {
 int listSize = list.size();
 while ((++index) < listSize && list.get(index).compareTo(value) == 0) {}
 if (inclusive) {
  index--;
return stayInBounds ? Math.min(list.size() - 1, index) : index;

代码示例来源:origin: plantuml/plantuml

public void add(V data) {
  final int pos = Collections.binarySearch(all, data, comparator);
  if (pos >= 0) {
    all.add(pos, data);
  } else {
    all.add(-pos - 1, data);
  }
  assert isSorted();
}

代码示例来源:origin: apache/usergrid

int searchIndex = Collections.binarySearch( resultsTracking, returnedValue, comparator );
  resultsTracking.add(returnedValue);
  mergedResults.add(returnedValue );
if (logger.isTraceEnabled()) logger.trace( "Candidate result set size is {}", mergedResults.size() );

代码示例来源:origin: apache/kylin

for (int i = 0; i < sorted.size(); i++) {
  String dictNum = dict.getValueFromId(i);
  assertEquals(sorted.get(i), new BigDecimal(dictNum));
  assertEquals(sorted.get(i), new BigDecimal(new String(dict.getValueByteFromId(i), StandardCharsets.UTF_8)));
  String randStr = randNumber();
  BigDecimal rand = new BigDecimal(randStr);
  int binarySearch = Collections.binarySearch(sorted, rand);
  if (binarySearch >= 0)
    continue;
  if (expectedHigherId >= sorted.size()) {
    try {
      dict.getIdFromValue(randStr, 1);

代码示例来源:origin: apache/hbase

/**
 * @param targetBoundaries The boundaries on which writers/files are separated.
 * @param majorRangeFrom Major range is the range for which at least one file should be written
 *          (because all files are included in compaction). majorRangeFrom is the left boundary.
 * @param majorRangeTo The right boundary of majorRange (see majorRangeFrom).
 */
public BoundaryMultiWriter(CellComparator comparator, List<byte[]> targetBoundaries,
  byte[] majorRangeFrom, byte[] majorRangeTo) throws IOException {
 super(comparator);
 this.boundaries = targetBoundaries;
 this.existingWriters = new ArrayList<>(this.boundaries.size() - 1);
 // "major" range (range for which all files are included) boundaries, if any,
 // must match some target boundaries, let's find them.
 assert (majorRangeFrom == null) == (majorRangeTo == null);
 if (majorRangeFrom != null) {
  majorRangeFromIndex =
    Arrays.equals(majorRangeFrom, StripeStoreFileManager.OPEN_KEY) ? 0 : Collections
      .binarySearch(boundaries, majorRangeFrom, Bytes.BYTES_COMPARATOR);
  majorRangeToIndex =
    Arrays.equals(majorRangeTo, StripeStoreFileManager.OPEN_KEY) ? boundaries.size()
      : Collections.binarySearch(boundaries, majorRangeTo, Bytes.BYTES_COMPARATOR);
  if (this.majorRangeFromIndex < 0 || this.majorRangeToIndex < 0) {
   throw new IOException("Major range does not match writer boundaries: ["
     + Bytes.toString(majorRangeFrom) + "] [" + Bytes.toString(majorRangeTo) + "]; from "
     + majorRangeFromIndex + " to " + majorRangeToIndex);
  }
 }
}

代码示例来源:origin: plantuml/plantuml

private int getValueSlow(double y) {
  final int idx = Collections.binarySearch(ys, y);
  if (idx >= 0) {
    return values.get(idx);
  }
  final int insertPoint = -idx - 1;
  if (insertPoint == 0) {
    return 0;
  }
  return values.get(insertPoint - 1);
}

代码示例来源:origin: apache/phoenix

@Test
public void testComparator() {
  // test ordering
  List<Bar> barList = new ArrayList<>();
  barList.add(b_c);
  barList.add(c_d);
  barList.add(a_b);
  Collections.sort(barList);
  assertEquals(a_b, barList.get(0));
  assertEquals(b_c, barList.get(1));
  assertEquals(c_d, barList.get(2));
  // test when a bar fully contains another
  Bar a_a = new Bar(bytesA, bytesA);
  assertEquals(0, a_b.compareTo(a_a));
  assertEquals(0, a_a.compareTo(a_b));
  assertEquals(1, b_c.compareTo(a_a));
  assertEquals(-1, a_a.compareTo(b_c));
  assertEquals(0, Collections.binarySearch(barList, a_a));
  assertEquals(1, Collections.binarySearch(barList, new Bar(bytesB, bytesB)));
  assertEquals(-4, Collections.binarySearch(barList, new Bar(Bytes.toBytes("e"), Bytes.toBytes("e"))));
  assertEquals(0, a_a.compareTo(a_a));
}

代码示例来源:origin: Bukkit/Bukkit

List<String> completion = null;
final int size = materials.size();
int i = Collections.binarySearch(materials, arg, String.CASE_INSENSITIVE_ORDER);
  String material = materials.get(i);
  if (StringUtil.startsWithIgnoreCase(material, arg)) {
    if (completion == null) {
      completion = new ArrayList<String>();
    completion.add(material);
  } else {
    break;

代码示例来源:origin: Netflix/Priam

@Override
public BigInteger findClosestToken(BigInteger tokenToSearch, List<BigInteger> tokenList) {
  Preconditions.checkArgument(!tokenList.isEmpty(), "token list must not be empty");
  List<BigInteger> sortedTokens = Ordering.natural().sortedCopy(tokenList);
  int index = Collections.binarySearch(sortedTokens, tokenToSearch, Ordering.natural());
  if (index < 0) {
    int i = Math.abs(index) - 1;
    if ((i >= sortedTokens.size())
        || (i > 0
            && sortedTokens
                    .get(i)
                    .subtract(tokenToSearch)
                    .compareTo(
                        tokenToSearch.subtract(sortedTokens.get(i - 1)))
                > 0)) --i;
    return sortedTokens.get(i);
  }
  return sortedTokens.get(index);
}

代码示例来源:origin: plantuml/plantuml

public void add(S newEntry) {
  final int r = Collections.binarySearch(allAsList, newEntry);
  if (r >= 0) {
    allAsList.add(r, newEntry);
  } else {
    allAsList.add(-1 - r, newEntry);
  }
  allAsSet.add(newEntry);
  assert isSorted();
}

相关文章

Collections类方法