Tabnine Logo
Collections.binarySearch
Code IndexAdd Tabnine to your IDE (free)

How to use
binarySearch
method
in
java.util.Collections

Best Java code snippets using java.util.Collections.binarySearch (Showing top 20 results out of 5,193)

Refine searchRefine arrow

  • List.get
  • List.size
  • List.add
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();
}
java.utilCollectionsbinarySearch

Javadoc

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.

Popular methods of Collections

  • emptyList
    Returns the empty list (immutable). This list is serializable.This example illustrates the type-safe
  • sort
  • singletonList
    Returns an immutable list containing only the specified object. The returned list is serializable.
  • unmodifiableList
    Returns an unmodifiable view of the specified list. This method allows modules to provide users with
  • emptyMap
    Returns the empty map (immutable). This map is serializable.This example illustrates the type-safe w
  • emptySet
    Returns the empty set (immutable). This set is serializable. Unlike the like-named field, this metho
  • unmodifiableMap
    Returns an unmodifiable view of the specified map. This method allows modules to provide users with
  • singleton
    Returns an immutable set containing only the specified object. The returned set is serializable.
  • unmodifiableSet
    Returns an unmodifiable view of the specified set. This method allows modules to provide users with
  • singletonMap
    Returns an immutable map, mapping only the specified key to the specified value. The returned map is
  • addAll
    Adds all of the specified elements to the specified collection. Elements to be added may be specifie
  • reverse
    Reverses the order of the elements in the specified list. This method runs in linear time.
  • addAll,
  • reverse,
  • unmodifiableCollection,
  • shuffle,
  • enumeration,
  • list,
  • synchronizedMap,
  • synchronizedList,
  • reverseOrder,
  • emptyIterator

Popular in Java

  • Making http requests using okhttp
  • scheduleAtFixedRate (ScheduledExecutorService)
  • onCreateOptionsMenu (Activity)
  • getExternalFilesDir (Context)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • FileOutputStream (java.io)
    An output stream that writes bytes to a file. If the output file exists, it can be replaced or appen
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • UnknownHostException (java.net)
    Thrown when a hostname can not be resolved.
  • BitSet (java.util)
    The BitSet class implements abit array [http://en.wikipedia.org/wiki/Bit_array]. Each element is eit
  • CountDownLatch (java.util.concurrent)
    A synchronization aid that allows one or more threads to wait until a set of operations being perfor
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now