java.util.Comparator Java Examples
The following examples show how to use
java.util.Comparator.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Solution.java From codekata with MIT License | 6 votes |
public String reorganizeString(String S) { int[][] table = new int[26][2]; for (int i = 0; i < S.length(); i++) table[S.charAt(i) - 'a'][1]++; for (int i = 0; i < 26; i++) table[i][0] = i; Arrays.sort(table, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o2[1] == o1[1] ? o1[0] - o2[0] : o2[1] - o1[1]; } }); if (table[0][1] > (S.length() + 1) / 2) return ""; char[] tmp = new char[S.length()]; int cursor = 0; for (int i = 0; i < 26; i++) { for (int j = 0; j < table[i][1]; j++) { if (cursor >= tmp.length) cursor = 1; tmp[cursor] = (char) (table[i][0] + 'a'); cursor += 2; } } return new String(tmp); }
Example #2
Source File: GroupChatAdapter.java From SendBird-Android with MIT License | 6 votes |
public void insertFailedMessages(List<BaseMessage> messages) { synchronized (mFailedMessageList) { for (BaseMessage message : messages) { String requestId = getRequestId(message); if (requestId.isEmpty()) { continue; } mResendingMessageSet.add(requestId); mFailedMessageList.add(message); } Collections.sort(mFailedMessageList, new Comparator<BaseMessage>() { @Override public int compare(BaseMessage m1, BaseMessage m2) { long x = m1.getCreatedAt(); long y = m2.getCreatedAt(); return (x < y) ? 1 : ((x == y) ? 0 : -1); } }); } notifyDataSetChanged(); }
Example #3
Source File: JobInProgress.java From RDFS with Apache License 2.0 | 6 votes |
/** * Given a candidate set of tasks, find and order the ones that * can be speculated and return the same. */ protected synchronized List<TaskInProgress> findSpeculativeTaskCandidates (Collection<TaskInProgress> list) { ArrayList<TaskInProgress> candidates = new ArrayList<TaskInProgress>(); long now = JobTracker.getClock().getTime(); Iterator<TaskInProgress> iter = list.iterator(); while (iter.hasNext()) { TaskInProgress tip = iter.next(); if (tip.canBeSpeculated(now)) { candidates.add(tip); } } if (candidates.size() > 0 ) { Comparator<TaskInProgress> LateComparator = new EstimatedTimeLeftComparator(now); Collections.sort(candidates, LateComparator); } return candidates; }
Example #4
Source File: CardTableRowSorter.java From opencards with BSD 2-Clause "Simplified" License | 6 votes |
public CardTableRowSorter(CardTableModel model) { super(model); // define the different column comparators // skip the name row because the default sorter does a great job here setComparator(1, new Comparator<StringifiedScheduleDate>() { public int compare(StringifiedScheduleDate o1, StringifiedScheduleDate o2) { return o1.compareTo(o2); } }); setComparator(2, new IntegerComparator()); setComparator(3, new IntegerComparator()); // apply the default sorting List<SortKey> sortKeys = new ArrayList<SortKey>(); sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING)); setSortKeys(sortKeys); sort(); }
Example #5
Source File: ImputerTrainer.java From ignite with Apache License 2.0 | 6 votes |
/** * Calculates the imputing values by frequencies keeping in the given dataset. * * @param dataset The dataset of frequencies for each feature aggregated in each partition.. * @return Most frequent value for each feature. */ private double[] calculateImputingValuesByTheMostFrequentValues( Dataset<EmptyContext, ImputerPartitionData> dataset) { Map<Double, Integer>[] frequencies = getAggregatedFrequencies(dataset); double[] res = new double[frequencies.length]; for (int i = 0; i < frequencies.length; i++) { Optional<Map.Entry<Double, Integer>> max = frequencies[i].entrySet() .stream() .max(Comparator.comparingInt(Map.Entry::getValue)); if (max.isPresent()) res[i] = max.get().getKey(); } return res; }
Example #6
Source File: LatchBasedInMemoryCloudDestination.java From ambry with Apache License 2.0 | 6 votes |
/** * Populates an ordered sequenced list of blobs in the specified partition in {@code nextEntries} {@link List}, * ordered by update time of blobs. Returns the updated {@link com.github.ambry.replication.FindToken}. * @param partitionPath the partition to query. * @param findToken the {@link com.github.ambry.replication.FindToken} specifying the boundary for the query. * @param maxTotalSizeOfEntries the cumulative size limit for the list of blobs returned. * @return {@link FindResult} instance that contains updated {@link CosmosUpdateTimeFindToken} object which can act as a bookmark for * subsequent requests, and {@link List} of {@link CloudBlobMetadata} entries. * @throws CloudStorageException */ private FindResult findUpdateTimeBasedEntries(String partitionPath, FindToken findToken, long maxTotalSizeOfEntries) { List<CloudBlobMetadata> nextEntries = new ArrayList<>(); CosmosUpdateTimeFindToken cosmosUpdateTimeFindToken = (CosmosUpdateTimeFindToken) findToken; List<CloudBlobMetadata> entries = new LinkedList<>(); for (BlobId blobId : map.keySet()) { if (map.get(blobId).getFirst().getLastUpdateTime() >= cosmosUpdateTimeFindToken.getLastUpdateTime()) { if (cosmosUpdateTimeFindToken.getLastUpdateTimeReadBlobIds().contains(map.get(blobId).getFirst().getId())) { continue; } entries.add(map.get(blobId).getFirst()); } } Collections.sort(entries, Comparator.comparingLong(CloudBlobMetadata::getLastUpdateTime)); List<CloudBlobMetadata> cappedRsults = CloudBlobMetadata.capMetadataListBySize(entries, maxTotalSizeOfEntries); nextEntries.addAll(cappedRsults); return new FindResult(nextEntries, CosmosUpdateTimeFindToken.getUpdatedToken(cosmosUpdateTimeFindToken, cappedRsults)); }
Example #7
Source File: TFIDFKeywordExtractor.java From cocolian-nlp with Apache License 2.0 | 6 votes |
/** * 获取从map中获取Top N 个关键字 * @param keywords * @param count * @return */ private List<String> extractTopN(Map<String, Integer> keywords, int count) { if (count > keywords.size()) count = keywords.size(); List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>( keywords.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { return o2.getValue() - o1.getValue(); } }); List<String> result = new ArrayList<String>(); for (Map.Entry<String, Integer> entry : list.subList(0, count)) { result.add(entry.getKey()); } return result; }
Example #8
Source File: NonTransactionalAdapterQueue.java From copper-engine with Apache License 2.0 | 6 votes |
public NonTransactionalAdapterQueue(Collection<String> adapterIds, AdapterCallPersisterFactory persistence, int transientQueueLength, int triggerReloadQueueLength, TransactionController ctrl, Batcher batcher) { this.transientQueueLength = transientQueueLength; this.triggerReloadQueueLength = triggerReloadQueueLength; this.persistence = persistence; this.adapterIds = new ArrayList<String>(adapterIds); this.ctrl = ctrl; this.batcher = batcher; this.queue = new PriorityBlockingQueue<AdapterCall>(transientQueueLength, new Comparator<AdapterCall>() { @Override public int compare(AdapterCall o1, AdapterCall o2) { if (o1.getPriority() < o2.getPriority()) return -1; if (o1.getPriority() > o2.getPriority()) return 1; return 0; } }); this.reloadThread = new ReloadThread(); }
Example #9
Source File: MCRXMLFunctions.java From mycore with GNU General Public License v3.0 | 6 votes |
/** * This only works with text nodes * @param nodes * @return the order of nodes maybe changes */ public static NodeList distinctValues(NodeList nodes) { SortedSet<Node> distinctNodeSet = new TreeSet<>(new Comparator<Node>() { @Override public int compare(Node node, Node t1) { String nodeValue = node.getNodeValue(); String nodeValue1 = t1.getNodeValue(); return Objects.equals(nodeValue1, nodeValue) ? 0 : -1; } }); for (int i = 0; i < nodes.getLength(); i++) { distinctNodeSet.add(nodes.item(i)); } return new SetNodeList(distinctNodeSet); }
Example #10
Source File: BaseMultiStartMultivariateRealOptimizer.java From astor with GNU General Public License v2.0 | 6 votes |
/** * Sort the optima from best to worst, followed by {@code null} elements. * * @param goal Goal type. */ private void sortPairs(final GoalType goal) { Arrays.sort(optima, new Comparator<RealPointValuePair>() { public int compare(final RealPointValuePair o1, final RealPointValuePair o2) { if (o1 == null) { return (o2 == null) ? 0 : 1; } else if (o2 == null) { return -1; } final double v1 = o1.getValue(); final double v2 = o2.getValue(); return (goal == GoalType.MINIMIZE) ? Double.compare(v1, v2) : Double.compare(v2, v1); } }); }
Example #11
Source File: Utils.java From fabric-sdk-java with Apache License 2.0 | 6 votes |
/** * Generate hash of a chaincode directory * * @param rootDir Root directory * @param chaincodeDir Channel code directory * @param hash Previous hash (if any) * @return hash of the directory * @throws IOException */ public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash) throws IOException { // Generate the project directory Path projectPath = null; if (rootDir == null) { projectPath = Paths.get(chaincodeDir); } else { projectPath = Paths.get(rootDir, chaincodeDir); } File dir = projectPath.toFile(); if (!dir.exists() || !dir.isDirectory()) { throw new IOException(format("The chaincode path \"%s\" is invalid", projectPath)); } StringBuilder hashBuilder = new StringBuilder(hash); Files.walk(projectPath) .sorted(Comparator.naturalOrder()) .filter(Files::isRegularFile) .map(Path::toFile) .forEach(file -> { try { byte[] buf = readFile(file); byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes(UTF_8)); hashBuilder.setLength(0); hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest()))); } catch (IOException ex) { throw new RuntimeException(format("Error while reading file %s", file.getAbsolutePath()), ex); } }); // If original hash and final hash are the same, it indicates that no new contents were found if (hashBuilder.toString().equals(hash)) { throw new IOException(format("The chaincode directory \"%s\" has no files", projectPath)); } return hashBuilder.toString(); }
Example #12
Source File: TimerExpiredTaskApplicationStubs.java From o2oa with GNU Affero General Public License v3.0 | 6 votes |
private ProcessStubs concreteProcessStubs(Business business, DateRange dateRange, ApplicationStub applicationStub) throws Exception { Set<String> ids = new HashSet<>(); ids.addAll(this.listProcessFromTask(business, dateRange, applicationStub)); ids.addAll(this.listProcessFromTaskCompleted(business, dateRange, applicationStub)); List<ProcessStub> list = new ArrayList<>(); for (String str : ids) { String name = this.getProcessName(business, dateRange, str); ProcessStub stub = new ProcessStub(); stub.setName(name); stub.setValue(str); stub.setApplicationCategory(applicationStub.getCategory()); stub.setApplicationName(applicationStub.getName()); stub.setApplicationValue(applicationStub.getValue()); stub.setActivityStubs(this.concreteActivityStubs(business, dateRange, stub)); list.add(stub); } list = list.stream() .sorted(Comparator.comparing(ProcessStub::getName, Comparator.nullsLast(String::compareTo))) .collect(Collectors.toList()); ProcessStubs stubs = new ProcessStubs(); stubs.addAll(list); return stubs; }
Example #13
Source File: WidgetThemes.java From SuntimesWidget with GNU General Public License v3.0 | 6 votes |
public static List<ThemeDescriptor> getSortedValues(final boolean defaultsFirst) { List<SuntimesTheme.ThemeDescriptor> themeDefs = getValues(); Collections.sort(themeDefs, new Comparator<ThemeDescriptor>() { @Override public int compare(SuntimesTheme.ThemeDescriptor o1, SuntimesTheme.ThemeDescriptor o2) { if (defaultsFirst) { if (o1.isDefault() && !o2.isDefault()) return -1; else if (o2.isDefault() && !o1.isDefault()) return 1; } return o1.displayString().compareToIgnoreCase(o2.displayString()); } }); return themeDefs; }
Example #14
Source File: IgniteCacheAbstractQuerySelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** * @param cache Ignite cache. * @throws Exception If failed. */ private void testPaginationGet(IgniteCache<Integer, Integer> cache) throws Exception { for (int i = 0; i < 50; i++) cache.put(i, i); QueryCursor<Cache.Entry<Integer, Integer>> q = cache.query(new SqlQuery<Integer, Integer>(Integer.class, "_key >= 0")); List<Cache.Entry<Integer, Integer>> list = new ArrayList<>(q.getAll()); Collections.sort(list, new Comparator<Cache.Entry<Integer, Integer>>() { @Override public int compare(Cache.Entry<Integer, Integer> e1, Cache.Entry<Integer, Integer> e2) { return e1.getKey().compareTo(e2.getKey()); } }); for (int i = 0; i < 50; i++) { Cache.Entry<Integer, Integer> e = list.get(i); assertEquals(i, (int)e.getKey()); assertEquals(i, (int)e.getValue()); } }
Example #15
Source File: KLeastNumbers.java From AtOffer with Apache License 2.0 | 6 votes |
/** * O(nlogk)的算法,特别适合处理海量数据 * 基于堆或者红黑树 * @param array * @param k * @return */ public ArrayList<Integer> getLeastNumbers(int[] array, int k) { if(array == null || array.length == 0 || k > array.length || k <= 0) { return new ArrayList<>(); } PriorityQueue<Integer> kLeastNumbers = new PriorityQueue<>(k, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); for (int i = 0; i < array.length; i++) { if(kLeastNumbers.size() < k) { kLeastNumbers.offer(array[i]); } else { if(kLeastNumbers.peek() > array[i]) { kLeastNumbers.poll(); kLeastNumbers.offer(array[i]); } } } return new ArrayList<>(kLeastNumbers); }
Example #16
Source File: PrimitiveSumMinMaxTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public void testBooleanMethods() { BinaryOperator<Boolean> and = Boolean::logicalAnd; BinaryOperator<Boolean> or = Boolean::logicalOr; BinaryOperator<Boolean> xor = Boolean::logicalXor; Comparator<Boolean> cmp = Boolean::compare; assertTrue(and.apply(true, true)); assertFalse(and.apply(true, false)); assertFalse(and.apply(false, true)); assertFalse(and.apply(false, false)); assertTrue(or.apply(true, true)); assertTrue(or.apply(true, false)); assertTrue(or.apply(false, true)); assertFalse(or.apply(false, false)); assertFalse(xor.apply(true, true)); assertTrue(xor.apply(true, false)); assertTrue(xor.apply(false, true)); assertFalse(xor.apply(false, false)); assertEquals(Boolean.TRUE.compareTo(Boolean.TRUE), cmp.compare(true, true)); assertEquals(Boolean.TRUE.compareTo(Boolean.FALSE), cmp.compare(true, false)); assertEquals(Boolean.FALSE.compareTo(Boolean.TRUE), cmp.compare(false, true)); assertEquals(Boolean.FALSE.compareTo(Boolean.FALSE), cmp.compare(false, false)); }
Example #17
Source File: MultiRowColumnIterator.java From usergrid with Apache License 2.0 | 6 votes |
/** * Create the iterator */ public MultiRowColumnIterator( final Keyspace keyspace, final ColumnFamily<R, C> cf, final ConsistencyLevel consistencyLevel, final ColumnParser<C, T> columnParser, final ColumnSearch<T> columnSearch, final Comparator<T> comparator, final Collection<R> rowKeys, final int pageSize ) { this.cf = cf; this.pageSize = pageSize; this.columnParser = columnParser; this.columnSearch = columnSearch; this.comparator = comparator; this.rowKeys = rowKeys; this.keyspace = keyspace; this.consistencyLevel = consistencyLevel; this.moreToReturn = true; // seenResults = new HashMap<>( pageSize * 10 ); }
Example #18
Source File: PinpointPluginTestRunner.java From pinpoint with Apache License 2.0 | 5 votes |
private Comparator<? super FrameworkMethod> comparator(final Sorter sorter) { return new Comparator<FrameworkMethod>() { public int compare(FrameworkMethod o1, FrameworkMethod o2) { return sorter.compare(describeChild(o1), describeChild(o2)); } }; }
Example #19
Source File: BKeyedGatherExample.java From twister2 with Apache License 2.0 | 5 votes |
@Override public void init(Config cfg, Set<Integer> targets) { if (targets.isEmpty()) { return; } this.lowestTarget = targets.stream().min(Comparator.comparingInt(o -> (Integer) o)).get(); }
Example #20
Source File: RegularImmutableTable.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
static <R, C, V> RegularImmutableTable<R, C, V> forCells(List<Cell<R, C, V>> cells, @Nullable final Comparator<? super R> rowComparator, @Nullable final Comparator<? super C> columnComparator) { checkNotNull(cells); if (rowComparator != null || columnComparator != null) { /* * This sorting logic leads to a cellSet() ordering that may not be expected and that isn't * documented in the Javadoc. If a row Comparator is provided, cellSet() iterates across the * columns in the first row, the columns in the second row, etc. If a column Comparator is * provided but a row Comparator isn't, cellSet() iterates across the rows in the first * column, the rows in the second column, etc. */ Comparator<Cell<R, C, V>> comparator = new Comparator<Cell<R, C, V>>() { @Override public int compare(Cell<R, C, V> cell1, Cell<R, C, V> cell2) { int rowCompare = (rowComparator == null) ? 0 : rowComparator.compare(cell1.getRowKey(), cell2.getRowKey()); if (rowCompare != 0) { return rowCompare; } return (columnComparator == null) ? 0 : columnComparator.compare(cell1.getColumnKey(), cell2.getColumnKey()); } }; Collections.sort(cells, comparator); } return forCellsInternal(cells, rowComparator, columnComparator); }
Example #21
Source File: DeploymentList.java From camunda-bpm-platform-osgi with Apache License 2.0 | 5 votes |
@Override protected Object doExecute() throws Exception { try { List<Deployment> deployments = engine.getRepositoryService().createDeploymentQuery().list(); Collections.sort(deployments, new Comparator<Deployment>() { @Override public int compare(Deployment d1, Deployment d2) { return d1.getDeploymentTime().compareTo(d2.getDeploymentTime()); } }); if (deployments.size() > 0) { String[][] data = new String[deployments.size()][HEADER.length]; int i = 0; for (Deployment d : deployments) { data[i++] = new String[]{ d.getId(), d.getName(), d.getDeploymentTime().toString()}; } ASCIITable.getInstance().printTable(HEADER, data); } else { System.out.println("There is no active deployment"); } } catch (Exception ex) { ex.printStackTrace(); } return null; }
Example #22
Source File: RenderSystem.java From Pacman_libGdx with MIT License | 5 votes |
@Override public void update(float deltaTime) { super.update(deltaTime); renderArray.sort(new Comparator<Entity>() { @Override public int compare(Entity o1, Entity o2) { TransformComponent transform1 = transformM.get(o1); TransformComponent transform2 = transformM.get(o2); return transform2.zIndex - transform1.zIndex; } }); batch.begin(); for (Entity entity : renderArray) { TransformComponent transform = transformM.get(entity); TextureComponent tex = rendererM.get(entity); float width = tex.region.getRegionWidth() / GameManager.PPM; float height = tex.region.getRegionHeight() / GameManager.PPM; float originX = width * 0.5f; float originY = height * 0.5f; batch.draw(tex.region, transform.pos.x - originX, transform.pos.y - originY, originX, originY, width, height, transform.scale.x, transform.scale.y, transform.rotation * MathUtils.radiansToDegrees); } batch.end(); renderArray.clear(); }
Example #23
Source File: Utility.java From Norii with Apache License 2.0 | 5 votes |
public static Entity[] sortUnits(final Entity[] sortedUnits) { Arrays.sort(sortedUnits, new Comparator<Entity>() { @Override public int compare(final Entity e1, final Entity e2) { if (e1.getCurrentInitiative() > e2.getCurrentInitiative()) { return 1; } else if (e1.getCurrentInitiative() < e2.getCurrentInitiative()) { return -1; } else { return 0; } } }); return sortedUnits; }
Example #24
Source File: DemoTaskBeanMulti.java From tbschedule with Apache License 2.0 | 5 votes |
@Override public Comparator<Long> getComparator() { return new Comparator<Long>() { public int compare(Long o1, Long o2) { return o1.compareTo(o2); } public boolean equals(Object obj) { return this == obj; } }; }
Example #25
Source File: Sort.java From attic-apex-malhar with Apache License 2.0 | 5 votes |
private void insertElement(List<T> accumulatedValue, T element, Comparator<T> comparator) { //binarySearch returns location if input exists else returns (-(insertion point) - 1) int index = Collections.binarySearch(accumulatedValue, element, comparator); index = index >= 0 ? index : (-index - 1); accumulatedValue.add(index, element); }
Example #26
Source File: Dumper.java From brooklyn-server with Apache License 2.0 | 5 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) static List<ConfigKey<?>> sortConfigKeys(Set<ConfigKey<?>> configs) { List result = new ArrayList(configs); Collections.sort(result, new Comparator<ConfigKey>() { @Override public int compare(ConfigKey arg0, ConfigKey arg1) { return arg0.getName().compareTo(arg1.getName()); } }); return result; }
Example #27
Source File: LanguageSelectActivity.java From Telegram with GNU General Public License v2.0 | 5 votes |
private void fillLanguages() { final LocaleController.LocaleInfo currentLocale = LocaleController.getInstance().getCurrentLocaleInfo(); Comparator<LocaleController.LocaleInfo> comparator = (o, o2) -> { if (o == currentLocale) { return -1; } else if (o2 == currentLocale) { return 1; } else if (o.serverIndex == o2.serverIndex) { return o.name.compareTo(o2.name); } if (o.serverIndex > o2.serverIndex) { return 1; } else if (o.serverIndex < o2.serverIndex) { return -1; } return 0; }; sortedLanguages = new ArrayList<>(); unofficialLanguages = new ArrayList<>(LocaleController.getInstance().unofficialLanguages); ArrayList<LocaleController.LocaleInfo> arrayList = LocaleController.getInstance().languages; for (int a = 0, size = arrayList.size(); a < size; a++) { LocaleController.LocaleInfo info = arrayList.get(a); if (info.serverIndex != Integer.MAX_VALUE) { sortedLanguages.add(info); } else { unofficialLanguages.add(info); } } Collections.sort(sortedLanguages, comparator); Collections.sort(unofficialLanguages, comparator); }
Example #28
Source File: ConcurrentSkipListMap.java From Java8CN with Apache License 2.0 | 5 votes |
final KeySpliterator<K,V> keySpliterator() { Comparator<? super K> cmp = comparator; for (;;) { // ensure h corresponds to origin p HeadIndex<K,V> h; Node<K,V> p; Node<K,V> b = (h = head).node; if ((p = b.next) == null || p.value != null) return new KeySpliterator<K,V>(cmp, h, p, null, (p == null) ? 0 : Integer.MAX_VALUE); p.helpDelete(b, p.next); } }
Example #29
Source File: Warehouse.java From Design-Patterns-and-SOLID-Principles-with-Java with MIT License | 5 votes |
public Collection<Order> getOrders() throws WarehouseException { return orderDao.getOrders() .stream() .sorted() .sorted(Comparator.comparing(Order::getId)) .collect(toUnmodifiableList()); }
Example #30
Source File: ArraysParallelSortHelpers.java From streamsupport with GNU General Public License v2.0 | 5 votes |
Sorter(CountedCompleter<?> par, T[] a, T[] w, int base, int size, int wbase, int gran, Comparator<? super T> comparator) { super(par); this.a = a; this.w = w; this.base = base; this.size = size; this.wbase = wbase; this.gran = gran; this.comparator = comparator; }