Example usage for java.util NavigableMap tailMap

List of usage examples for java.util NavigableMap tailMap

Introduction

In this page you can find the example usage for java.util NavigableMap tailMap.

Prototype

NavigableMap<K, V> tailMap(K fromKey, boolean inclusive);

Source Link

Document

Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey .

Usage

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.tailMap(1, true) + "\n");

}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private NavigableMap<Cell, byte[]> getReadsInRange(String table, Entry<RangeRequest, byte[]> e,
        RangeRequest range) {/*w ww. j  ava 2 s  .  c om*/
    NavigableMap<Cell, byte[]> reads = getReadsForTable(table);
    if (range.getStartInclusive().length != 0) {
        reads = reads.tailMap(Cells.createSmallestCellForRow(range.getStartInclusive()), true);
    }
    if (range.getEndExclusive().length != 0) {
        reads = reads.headMap(Cells.createSmallestCellForRow(range.getEndExclusive()), false);
    }
    ConcurrentNavigableMap<Cell, byte[]> writes = writesByTable.get(table);
    if (writes != null) {
        reads = Maps.filterKeys(reads, Predicates.not(Predicates.in(writes.keySet())));
    }
    return reads;
}

From source file:com.google.cloud.dns.testing.LocalDnsHelper.java

/**
 * Lists changes. Next page token is the ID of the last change listed.
 *//*  w w  w  .j  a v a  2  s .com*/
@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 testTailMap_viewPutRemove() {
    K[] keys = getSortedKeys();/*from ww  w.  j  a  v  a2 s. c  o  m*/
    V[] values = getSortedValues();

    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[3], values[3]);

    NavigableMap<K, V> tailMap = map.tailMap(keys[1], true);
    try {
        tailMap.put(keys[0], values[0]);
        fail();
    } catch (IllegalArgumentException e) {
        // must not insert value outside the range
    }
    tailMap.remove(keys[0]);
    assertEquals(2, tailMap.size());
    assertEquals(3, map.size());
    assertTrue(map.containsKey(keys[0]));

    tailMap.put(keys[2], values[2]);
    assertEquals(3, tailMap.size());
    assertEquals(4, map.size());
    assertTrue(map.containsKey(keys[2]));
    assertTrue(tailMap.containsKey(keys[2]));

    tailMap.remove(keys[2]);
    assertFalse(map.containsKey(keys[2]));
    assertFalse(tailMap.containsKey(keys[2]));

    tailMap.clear();
    assertEquals(0, tailMap.size());
    assertEquals(1, map.size());
    assertTrue(map.containsKey(keys[0]));
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testHeadMapLjava_lang_ObjectZL() {
    K[] keys = getSortedKeys();//from   w w w. ja v a  2s  .co m
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }

    // normal case
    SortedMap<K, V> subMap = map.headMap(keys[2], true);
    assertEquals(3, subMap.size());
    subMap = map.headMap(keys[3], true);
    assertEquals(4, subMap.size());
    for (int i = 0; i < 4; i++) {
        assertEquals(values[i], subMap.get(keys[i]));
    }
    subMap = map.headMap(keys[2], false);
    assertEquals(2, subMap.size());
    assertNull(subMap.get(keys[3]));

    // Exceptions
    assertEquals(0, map.headMap(keys[0], false).size());

    try {
        map.headMap(null, true);
        assertTrue("expected exception", useNullKey());
    } catch (NullPointerException e) {
        assertFalse("unexpected NPE", useNullKey());
    }

    try {
        map.headMap(null, false);
        assertTrue("expected exception", useNullKey());
    } catch (NullPointerException e) {
        assertFalse("unexpected NPE", useNullKey());
    }

    subMap = map.headMap(keys[2]);
    assertEquals(2, subMap.size());
    try {
        subMap.put(keys[2], values[2]);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    assertEquals(keys.length, map.size());
    subMap = map.headMap(keys[2], true);
    assertEquals(3, subMap.size());
    subMap.remove(keys[1]);
    assertFalse(subMap.containsKey(keys[1]));
    assertFalse(subMap.containsValue(values[1]));
    assertFalse(map.containsKey(keys[1]));
    assertFalse(map.containsValue(values[1]));
    assertEquals(2, subMap.size());
    assertEquals(keys.length - 1, map.size());

    subMap.put(keys[1], values[1]);

    try {
        subMap.subMap(keys[1], keys[3]);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        subMap.subMap(keys[3], keys[1]);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }

    if (useNullKey() && useNullValue()) {
        map.put(null, null);

        subMap = map.headMap(null, true);
        assertEquals(1, subMap.size());
        assertTrue(subMap.containsValue(null));
        assertNull(subMap.get(null));

        subMap = map.subMap(null, false, keys[2], true);
        assertEquals(3, subMap.size());

        Set<K> keySet = subMap.keySet();
        assertEquals(3, keySet.size());

        Set<Map.Entry<K, V>> entrySet = subMap.entrySet();
        assertEquals(3, entrySet.size());

        Collection<V> valueCollection = subMap.values();
        assertEquals(3, valueCollection.size());

        map.remove(null);
    }

    // head map of head map
    NavigableMap<K, V> headMap = map.headMap(keys[3], true);
    assertEquals(4, headMap.size());
    headMap = headMap.headMap(keys[3], false);
    assertEquals(3, headMap.size());
    headMap = headMap.headMap(keys[2], false);
    assertEquals(2, headMap.size());
    headMap = headMap.tailMap(keys[0], false);
    assertEquals(1, headMap.size());
    headMap = headMap.tailMap(keys[1], false);
    assertEquals(0, headMap.size());
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testDescendingMap() {
    K[] keys = getSortedKeys();//from   ww w  . j a v  a  2 s .c o m
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);

    NavigableMap<K, V> descendingMap = map.descendingMap();
    _assertEquals(descendingMap, map.descendingMap());

    map.put(keys[1], values[1]);
    _assertEquals(map, descendingMap.descendingMap());
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());

    descendingMap.put(keys[2], values[2]);
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());
    _assertEquals(map.entrySet(), descendingMap.descendingMap().entrySet());

    descendingMap.remove(keys[1]);
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());

    descendingMap.clear();
    assertEquals(0, descendingMap.size());
    assertEquals(0, map.size());

    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[2], values[2]);
    assertEquals(3, descendingMap.size());

    NavigableMap<K, V> headMap = descendingMap.headMap(keys[1], false);
    assertEquals(1, headMap.size());
    assertTrue(headMap.containsKey(keys[2]));

    NavigableMap<K, V> subMap = descendingMap.subMap(keys[2], true, keys[1], true);
    assertEquals(2, subMap.size());
    assertTrue(subMap.containsKey(keys[1]));
    assertTrue(subMap.containsKey(keys[2]));

    NavigableMap<K, V> tailMap = descendingMap.tailMap(keys[1], false);
    assertEquals(1, tailMap.size());
    assertTrue(tailMap.containsKey(keys[0]));
}

From source file:org.apache.blur.kvs.HdfsKeyValueStore.java

private Iterable<Entry<BytesRef, BytesRef>> getIterable(BytesRef key, NavigableMap<BytesRef, Value> pointers) {
    if (key == null) {
        key = pointers.firstKey();// ww  w. ja  va 2s  .  co  m
    }
    NavigableMap<BytesRef, Value> tailMap = pointers.tailMap(key, true);
    return getIterable(tailMap);
}

From source file:org.apache.hadoop.hbase.MetaTableAccessor.java

/**
 * Returns an HRegionLocationList extracted from the result.
 * @return an HRegionLocationList containing all locations for the region range or null if
 *  we can't deserialize the result./* w  w w  .j a  va2s.c o  m*/
 */
@Nullable
public static RegionLocations getRegionLocations(final Result r) {
    if (r == null)
        return null;
    HRegionInfo regionInfo = getHRegionInfo(r, getRegionInfoColumn());
    if (regionInfo == null)
        return null;

    List<HRegionLocation> locations = new ArrayList<HRegionLocation>(1);
    NavigableMap<byte[], NavigableMap<byte[], byte[]>> familyMap = r.getNoVersionMap();

    locations.add(getRegionLocation(r, regionInfo, 0));

    NavigableMap<byte[], byte[]> infoMap = familyMap.get(getCatalogFamily());
    if (infoMap == null)
        return new RegionLocations(locations);

    // iterate until all serverName columns are seen
    int replicaId = 0;
    byte[] serverColumn = getServerColumn(replicaId);
    SortedMap<byte[], byte[]> serverMap = infoMap.tailMap(serverColumn, false);
    if (serverMap.isEmpty())
        return new RegionLocations(locations);

    for (Map.Entry<byte[], byte[]> entry : serverMap.entrySet()) {
        replicaId = parseReplicaIdFromServerColumn(entry.getKey());
        if (replicaId < 0) {
            break;
        }
        HRegionLocation location = getRegionLocation(r, regionInfo, replicaId);
        // In case the region replica is newly created, it's location might be null. We usually do not
        // have HRL's in RegionLocations object with null ServerName. They are handled as null HRLs.
        if (location == null || location.getServerName() == null) {
            locations.add(null);
        } else {
            locations.add(location);
        }
    }

    return new RegionLocations(locations);
}

From source file:org.wisdom.raml.visitor.RamlControllerVisitor.java

/**
 * Navigate through the Controller routes, and create {@link org.raml.model.Resource} from them.
 * If the <code>parent</code> is not null, then the created route will be added has children of the parent, otherwise
 * a new Resource is created and will be added directly to the <code>raml</code> model.
 *
 * @param routes The @{link ControllerRoute}
 * @param parent The parent {@link Resource}
 * @param raml   The {@link Raml} model/*from w  ww .j a v  a2  s.  c o  m*/
 */
private void navigateTheRoutes(NavigableMap<String, Collection<ControllerRouteModel<Raml>>> routes,
        Resource parent, Raml raml) {
    //nothing to see here
    if (routes == null || routes.isEmpty()) {
        return;
    }

    String headUri = routes.firstKey();
    LOGGER.debug("Routes " + routes.toString());
    LOGGER.debug("Parent " + parent);
    Collection<ControllerRouteModel<Raml>> siblings = routes.get(headUri);
    String relativeUri;

    Resource res = new Resource();
    if (parent != null) {
        res.setParentResource(parent);
        res.setParentUri(parent.getUri());
        //Get the relative part of the url
        relativeUri = normalizeActionPath(parent, headUri);
        res.setRelativeUri(relativeUri);
        parent.getResources().put(res.getRelativeUri(), res);
    } else {
        // We don't have a parent, check whether we should create one.
        if (headUri.endsWith("/")) {
            // We have to create a 'fake' parent when we have such kind of url: /foo/
            // We create a parent /foo and a sub-resource /, this is because /foo and /foo/ are different
            // Create a parent - this parent doest not have any action attached.
            String parentUri = normalizeParentPath(headUri);

            // However we do have a tricky case here, if parentURi == "/", we are the parent.
            if (!parentUri.equals("/")) {
                parent = new Resource();
                parent.setParentUri("");
                parent.setRelativeUri(parentUri);
                raml.getResources().put(parentUri, parent);

                // Now manage the current resource, it's uri is necessarily /
                relativeUri = "/";
                res.setParentUri(parent.getUri());
                res.setRelativeUri(relativeUri);
                parent.getResources().put(relativeUri, res);
            } else {
                // We are the root.
                res.setParentUri("");
                relativeUri = normalizeParentPath(headUri);
                res.setRelativeUri(relativeUri);
                raml.getResources().put(res.getRelativeUri(), res);
            }
        } else {
            // No parent
            res.setParentUri("");
            relativeUri = normalizeParentPath(headUri);
            res.setRelativeUri(relativeUri);
            raml.getResources().put(res.getRelativeUri(), res);
        }
    }

    //Add the action from the brother routes
    for (ControllerRouteModel<Raml> bro : siblings) {
        addActionFromRouteElem(bro, res);
    }

    //visit the children route
    NavigableMap<String, Collection<ControllerRouteModel<Raml>>> child = routes.tailMap(headUri, false);

    //no more route element
    if (child.isEmpty()) {
        return;
    }

    final String next = child.firstKey();
    final Resource maybeParent = findParent(next, raml);
    navigateTheRoutes(child, maybeParent, raml);
}