List of usage examples for java.util NavigableMap descendingKeySet
NavigableSet<K> descendingKeySet();
From source file:Main.java
public static void main(String[] args) { NavigableMap<Integer, String> map = new TreeMap<Integer, String>(); map.put(2, "two"); map.put(1, "one"); map.put(3, "three"); System.out.println(map.descendingKeySet() + "\n"); }
From source file:com.google.cloud.dns.testing.LocalDnsHelper.java
/** * Lists changes. Next page token is the ID of the last change listed. *//*from w w w . java 2s .c om*/ @VisibleForTesting Response listChanges(String projectId, String zoneName, String query) { Map<String, Object> options = OptionParsers.parseListChangesOptions(query); Response response = checkListOptions(options); if (response != null) { return response; } ZoneContainer zoneContainer = findZone(projectId, zoneName); if (zoneContainer == null) { return Error.NOT_FOUND.response( String.format("The 'parameters.managedZone' resource named '%s' does not exist", zoneName)); } // take a sorted snapshot of the current change list NavigableMap<Integer, Change> changes = new TreeMap<>(); for (Change c : zoneContainer.changes()) { if (c.getId() != null) { changes.put(Integer.valueOf(c.getId()), c); } } String[] fields = (String[]) options.get("fields"); String sortOrder = (String) options.get("sortOrder"); String pageToken = (String) options.get("pageToken"); Integer maxResults = options.get("maxResults") == null ? null : Integer.valueOf((String) options.get("maxResults")); // as the only supported field is change sequence, we are not reading sortBy NavigableSet<Integer> keys; if ("descending".equals(sortOrder)) { keys = changes.descendingKeySet(); } else { keys = changes.navigableKeySet(); } Integer from = null; try { from = Integer.valueOf(pageToken); } catch (NumberFormatException ex) { // ignore page token } keys = from != null ? keys.tailSet(from, false) : keys; NavigableMap<Integer, Change> fragment = from != null && changes.containsKey(from) ? changes.tailMap(from, false) : changes; boolean sizeReached = false; boolean hasMorePages = false; LinkedList<String> serializedResults = new LinkedList<>(); String lastChangeId = null; for (Integer key : keys) { Change change = fragment.get(key); if (sizeReached) { // we do not add this, just note that there would be more and there should be a token hasMorePages = true; break; } else { lastChangeId = change.getId(); try { serializedResults.addLast(jsonFactory.toString(OptionParsers.extractFields(change, fields))); } catch (IOException e) { return Error.INTERNAL_ERROR.response( String.format("Error when serializing change %s in managed zone %s in project %s", lastChangeId, zoneName, projectId)); } } sizeReached = maxResults != null && maxResults.equals(serializedResults.size()); } boolean includePageToken = hasMorePages && (fields == null || Arrays.asList(fields).contains("nextPageToken")); return toListResponse(serializedResults, "changes", lastChangeId, includePageToken); }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testDescendingKeySet() { K[] keys = getSortedKeys();/*from w ww . ja va 2 s . c o m*/ V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); map.put(keys[0], values[0]); NavigableSet<K> keySet = map.descendingKeySet(); _assertEquals(keySet, map.descendingKeySet()); map.put(keys[1], values[1]); map.put(keys[2], values[2]); _assertEquals(reverseCollection(keySet), keySet); _assertEquals(map.keySet(), keySet.descendingSet()); }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
@SuppressWarnings("ModifyingCollectionWithItself") public void testDescendingKeySet_viewPut() { K[] keys = getSortedKeys();//from www. j a v a2 s .c o m V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); map.put(keys[0], values[0]); Set<K> keySet = map.descendingKeySet(); assertEquals(1, keySet.size()); map.put(keys[1], values[1]); assertEquals(2, keySet.size()); try { keySet.add(keys[2]); fail(); } catch (Exception e) { // java.util.NavigableMap.navigableKeySet() does not support add } try { keySet.addAll(keySet); fail(); } catch (Exception e) { // java.util.NavigableMap.navigableKeySet() does not support addAll } }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
public void testDescendingKeySet_viewRemove() { K[] keys = getSortedKeys();/*from w w w. j av a 2 s . c o m*/ V[] values = getSortedValues(); NavigableMap<K, V> map = createNavigableMap(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); Set<K> keySet = map.descendingKeySet(); assertEquals(2, keySet.size()); map.remove(keys[1]); assertEquals(1, keySet.size()); map.put(keys[1], values[1]); keySet.remove(keys[0]); assertEquals(1, map.size()); assertEquals(1, keySet.size()); assertEquals(keys[1], keySet.iterator().next()); keySet.clear(); assertEquals(0, map.size()); assertEquals(0, keySet.size()); }
From source file:com.google.gwt.emultest.java.util.TreeMapTest.java
@SuppressWarnings("unchecked") public void testDescendingKeySet_iterator() { NavigableMap<K, V> map = createNavigableMap(); map.putAll(makeFullMap());/* w w w . j a v a 2 s . c om*/ resetFull(); ArrayList<K> keys = new ArrayList<K>(); for (Object key : getSampleKeys()) { keys.add((K) key); } // JDK < 7 does not handle null keys correctly. if (useNullKey() && TestUtils.isJvm() && TestUtils.getJdkVersion() < 7) { map.remove(null); keys.remove(null); } Comparator<? super K> cmp = ((TreeMap<K, V>) map).comparator(); Collections.sort(keys, Collections.reverseOrder(cmp)); Iterator<K> it = map.descendingKeySet().iterator(); for (K key : keys) { assertTrue(it.hasNext()); K rem = it.next(); it.remove(); assertEquals(key, rem); } try { it.next(); fail("should throw NoSuchElementException"); } catch (NoSuchElementException expected) { } _assertEmpty(map); }
From source file:com.mirth.connect.server.controllers.DonkeyMessageController.java
private List<MessageSearchResult> searchMessages(MessageFilter filter, String channelId, int offset, int limit) { long startTime = System.currentTimeMillis(); FilterOptions filterOptions = new FilterOptions(filter, channelId); long maxMessageId = filterOptions.getMaxMessageId(); long minMessageId = filterOptions.getMinMessageId(); Long localChannelId = ChannelController.getInstance().getLocalChannelId(channelId); Map<String, Object> params = getBasicParameters(filter, localChannelId); try {/*from w w w.ja va 2 s . com*/ NavigableMap<Long, MessageSearchResult> messages = new TreeMap<Long, MessageSearchResult>(); SqlSession session = SqlConfig.getSqlSessionManager(); int offsetRemaining = offset; /* * If the limit is greater than the default batch size, use the limit, but cap it at * 50000. */ long batchSize = Math.min(Math.max(limit, 500), 50000); long totalSearched = 0; while (messages.size() < limit && maxMessageId >= minMessageId) { /* * Slowly increase the batch size in case all the necessary results are found early * on. */ if (totalSearched >= 100000 && batchSize < 50000) { batchSize = 50000; } else if (totalSearched >= 10000 && batchSize < 10000) { batchSize = 10000; } else if (totalSearched >= 1000 && batchSize < 1000) { batchSize = 1000; } /* * Search in descending order so that messages will be found from the greatest to * lowest message id */ long currentMinMessageId = Math.max(maxMessageId - batchSize + 1, minMessageId); params.put("maxMessageId", maxMessageId); params.put("minMessageId", currentMinMessageId); maxMessageId -= batchSize; totalSearched += batchSize; Map<Long, MessageSearchResult> foundMessages = searchAll(session, params, filter, localChannelId, false, filterOptions); if (!foundMessages.isEmpty()) { /* * Skip results until there is no offset remaining. This is required when * viewing results beyond the first page */ if (offsetRemaining >= foundMessages.size()) { offsetRemaining -= foundMessages.size(); } else if (offsetRemaining == 0) { messages.putAll(foundMessages); } else { NavigableMap<Long, MessageSearchResult> orderedMessages = new TreeMap<Long, MessageSearchResult>( foundMessages); while (offsetRemaining-- > 0) { orderedMessages.pollLastEntry(); } messages.putAll(orderedMessages); } } } // Remove results beyond the limit requested while (messages.size() > limit) { messages.pollFirstEntry(); } List<MessageSearchResult> results = new ArrayList<MessageSearchResult>(messages.size()); /* * Now that we have the message and metadata ids that should be returned as the result, * we need to retrieve the message data for those. */ if (!messages.isEmpty()) { Iterator<Long> iterator = messages.descendingKeySet().iterator(); while (iterator.hasNext()) { Map<String, Object> messageParams = new HashMap<String, Object>(); messageParams.put("localChannelId", localChannelId); ListRangeIterator listRangeIterator = new ListRangeIterator(iterator, ListRangeIterator.DEFAULT_LIST_LIMIT, false, null); while (listRangeIterator.hasNext()) { ListRangeItem item = listRangeIterator.next(); List<Long> list = item.getList(); Long startRange = item.getStartRange(); Long endRange = item.getEndRange(); if (list != null || (startRange != null && endRange != null)) { if (list != null) { messageParams.remove("minMessageId"); messageParams.remove("maxMessageId"); messageParams.put("includeMessageList", StringUtils.join(list, ",")); } else { messageParams.remove("includeMessageList"); messageParams.put("minMessageId", endRange); messageParams.put("maxMessageId", startRange); } // Get the current batch of results List<MessageSearchResult> currentResults = session .selectList("Message.selectMessagesById", messageParams); // Add the metadata ids to each result for (MessageSearchResult currentResult : currentResults) { currentResult.setMetaDataIdSet( messages.get(currentResult.getMessageId()).getMetaDataIdSet()); } // Add the current batch to the final list of results results.addAll(currentResults); } } } } return results; } finally { long endTime = System.currentTimeMillis(); logger.debug("Search executed in " + (endTime - startTime) + "ms"); } }
From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.java
/** * Get the entry position that come before the specified position in the message stream, using information from the * ledger list and each ledger entries count. * * @param position// w ww . j a va 2 s. c om * the current position * @return the previous position */ PositionImpl getPreviousPosition(PositionImpl position) { if (position.getEntryId() > 0) { return PositionImpl.get(position.getLedgerId(), position.getEntryId() - 1); } // The previous position will be the last position of an earlier ledgers NavigableMap<Long, LedgerInfo> headMap = ledgers.headMap(position.getLedgerId(), false); if (headMap.isEmpty()) { // There is no previous ledger, return an invalid position in the current ledger return PositionImpl.get(position.getLedgerId(), -1); } // We need to find the most recent non-empty ledger for (long ledgerId : headMap.descendingKeySet()) { LedgerInfo li = headMap.get(ledgerId); if (li.getEntries() > 0) { return PositionImpl.get(li.getLedgerId(), li.getEntries() - 1); } } // in case there are only empty ledgers, we return a position in the first one return PositionImpl.get(headMap.firstEntry().getKey(), -1); }
From source file:org.apache.sling.distribution.serialization.impl.vlt.VltUtils.java
private static void initFilterSet(PathFilterSet filterSet, NavigableMap<String, List<String>> globalFilters, List<String> patterns) { // add the most specific filter rules String root = filterSet.getRoot(); for (String key : globalFilters.descendingKeySet()) { if (root.startsWith(key)) { patterns.addAll(globalFilters.get(key)); break; }/*from ww w.j a va 2s.c om*/ } for (String pattern : patterns) { PathFilterSet.Entry<DefaultPathFilter> entry = extractPathPattern(pattern); if (entry.isInclude()) { filterSet.addInclude(entry.getFilter()); } else { filterSet.addExclude(entry.getFilter()); } } }