Example usage for java.util SortedMap tailMap

List of usage examples for java.util SortedMap tailMap

Introduction

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

Prototype

SortedMap<K, V> tailMap(K fromKey);

Source Link

Document

Returns a view of the portion of this map whose keys are greater than or equal to fromKey .

Usage

From source file:Main.java

public static void main(String[] args) {
    SortedMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
    sortedMap.put("A", 1);
    sortedMap.put("B", 2);
    sortedMap.put("C", 3);
    sortedMap.put("D", 4);
    sortedMap.put("E", 5);
    sortedMap.put("java2s", 6);

    SortedMap<String, Integer> map = sortedMap.tailMap("C");
    System.out.println(map);//from  w w w.  j ava2 s  .  c  o  m

}

From source file:FocusTraversalExample.java

public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
    if (!(aComponent instanceof JButton)) {
        return null;
    }/* w w  w  .  j  a  va  2  s.  co m*/
    SortedMap buttons = getSortedButtons(focusCycleRoot);
    // Find all buttons after the current one.
    String nextName = ((JButton) aComponent).getText() + "\0";
    SortedMap nextButtons = buttons.tailMap(nextName);
    if (nextButtons.isEmpty()) { // Wrapped back to beginning
        if (!buttons.isEmpty()) {
            return (Component) buttons.get(buttons.firstKey());
        }
        return null; // Degenerate case of no buttons.
    }
    return (Component) nextButtons.get(nextButtons.firstKey());
}

From source file:hudson.Functions.java

/**
 * Creates a sub map by using the given range (both ends inclusive).
 *//*  ww  w  .j  a  v  a2s  .co  m*/
public static <V> SortedMap<Integer, V> filter(SortedMap<Integer, V> map, String from, String to) {
    if (from == null && to == null)
        return map;
    if (to == null)
        return map.headMap(Integer.parseInt(from) - 1);
    if (from == null)
        return map.tailMap(Integer.parseInt(to));

    return map.subMap(Integer.parseInt(to), Integer.parseInt(from) - 1);
}

From source file:com.haulmont.cuba.web.sys.WebJarResourceResolver.java

protected String getFullPath(SortedMap<String, String> pathIndex, String partialPath) {
    if (partialPath.charAt(0) == '/') {
        partialPath = partialPath.substring(1);
    }/* ww  w .  j  a v  a2 s  .  c  o m*/

    String reversePartialPath = reversePath(partialPath);

    SortedMap<String, String> fullPathTail = pathIndex.tailMap(reversePartialPath);

    if (fullPathTail.size() == 0) {
        if (log.isTraceEnabled()) {
            printNotFoundTraceInfo(pathIndex, partialPath);
        }
        throwNotFoundException(partialPath);
    }

    Iterator<Map.Entry<String, String>> fullPathTailIterator = fullPathTail.entrySet().iterator();
    Map.Entry<String, String> fullPathEntry = fullPathTailIterator.next();
    if (!fullPathEntry.getKey().startsWith(reversePartialPath)) {
        if (log.isTraceEnabled()) {
            printNotFoundTraceInfo(pathIndex, partialPath);
        }
        throwNotFoundException(partialPath);
    }
    String fullPath = fullPathEntry.getValue();

    if (fullPathTailIterator.hasNext()) {
        List<String> matches = null;

        while (fullPathTailIterator.hasNext()) {
            Map.Entry<String, String> next = fullPathTailIterator.next();
            if (next.getKey().startsWith(reversePartialPath)) {
                if (matches == null) {
                    matches = new ArrayList<>();
                }
                matches.add(next.getValue());
            } else {
                break;
            }
        }

        if (matches != null) {
            matches.add(fullPath);
            throw new MultipleMatchesException("Multiple matches found for " + partialPath
                    + ". Please provide a more specific path, for example by including a version number.",
                    matches);
        }
    }

    return fullPath;
}

From source file:cerrla.LocalCrossEntropyDistribution.java

/**
 * Generates a policy from the current distribution.
 * /*from w ww . j  a  v a2 s .c  om*/
 * @param existingSubGoals
 *            A collection of all existing sub-goals in the parent policy
 *            this policy is to be put into.
 * @return A newly generated policy from the current distribution.
 */
public ModularPolicy generatePolicy(Collection<ModularPolicy> existingSubGoals) {
    // If testing greedy policies
    if (Config.getInstance().getGeneratorFile() != null) {
        if (bestPolicy_ == null || testEpisode_ >= ProgramArgument.TEST_ITERATIONS.intValue()) {
            SortedMap<Integer, RelationalPolicy> greedyPolicies = policyGenerator_.getGreedyPolicyMap();
            SortedMap<Integer, RelationalPolicy> nextKey = greedyPolicies.tailMap(currentEpisode_ + 1);

            if (ProgramArgument.TESTING.booleanValue()) {
                currentEpisode_ = greedyPolicies.lastKey();
                bestPolicy_ = new ModularPolicy(greedyPolicies.get(currentEpisode_), this);
                testEpisode_ = 0;
            } else if (nextKey == null || nextKey.isEmpty()) {
                // End of testing. Exit.
                bestPolicyEpisode_ = ProgramArgument.TEST_ITERATIONS.intValue();
            } else {
                // Next policy and next episode.
                currentEpisode_ = nextKey.firstKey();
                bestPolicy_ = new ModularPolicy(greedyPolicies.get(currentEpisode_), this);
                testEpisode_ = 0;
            }
        }

        bestPolicy_.clearPolicyRewards();
        return bestPolicy_;
    }

    if (frozen_ && state_ == AlgorithmState.BEST_POLICY) {
        bestPolicy_.clearPolicyRewards();
        return bestPolicy_;
    }

    // Initialise undertested
    if (undertestedPolicies_ == null)
        undertestedPolicies_ = new LinkedList<ModularPolicy>();

    // If there remains an undertested policy not already in the parent
    // policy, use that
    for (Iterator<ModularPolicy> iter = undertestedPolicies_.iterator(); iter.hasNext();) {
        ModularPolicy undertested = iter.next();
        if (undertested.shouldRegenerate() || !isValidSample(undertested, false))
            // If the element is fully tested, remove it.
            iter.remove();
        else if (!existingSubGoals.contains(undertested)) {
            // If the parent policy doesn't already contain the undertested
            // policy, return it.
            undertested.clearChildren();
            return undertested;
        }
    }

    // Otherwise generate a new policy
    RelationalPolicy newPol = policyGenerator_.generatePolicy(true, false);
    ModularPolicy newModPol = null;
    if (newPol instanceof ModularPolicy)
        newModPol = new ModularPolicy((ModularPolicy) newPol);
    else
        newModPol = new ModularPolicy(newPol, this);
    undertestedPolicies_.add(newModPol);
    return newModPol;
}

From source file:edu.mit.ll.graphulo.pig.backend.GraphuloOneTableStorage.java

@Override
protected Tuple getTuple(Key key, Value value) throws IOException {
    SortedMap<Key, Value> rowKVs = WholeRowIterator.decodeRow(key, value);
    Tuple tuple = TupleFactory.getInstance().newTuple(columns.size() + 1);

    final Text cfHolder = new Text();
    final Text cqHolder = new Text();
    final Text row = key.getRow();
    int tupleOffset = 0;

    tuple.set(tupleOffset, new DataByteArray(Text.decode(row.getBytes(), 0, row.getLength())));

    for (Column column : this.columns) {
        tupleOffset++;/*ww w  . ja va2  s. c  om*/

        switch (column.getType()) {
        case LITERAL:
            cfHolder.set(column.getColumnFamily());
            if (null != column.getColumnQualifier()) {
                cqHolder.set(column.getColumnQualifier());
            } else {
                cqHolder.set(EMPTY_TEXT);
            }

            // Get the key where our literal would exist (accounting for
            // "colf:colq" or "colf:" empty colq)
            Key literalStartKey = new Key(row, cfHolder, cqHolder);

            SortedMap<Key, Value> tailMap = rowKVs.tailMap(literalStartKey);

            // Find the element
            if (tailMap.isEmpty()) {
                tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
            } else {
                Key actualKey = tailMap.firstKey();

                // Only place it in the tuple if it matches the user
                // request, avoid using a value from a
                // key with the wrong colqual
                if (0 == literalStartKey.compareTo(actualKey, PartialKey.ROW_COLFAM_COLQUAL)) {
                    tuple.set(tupleOffset, new DataByteArray(tailMap.get(actualKey).get()));
                } else {
                    // This row doesn't have the column we were looking for
                    tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
                }
            }

            break;
        case COLFAM_PREFIX:
            cfHolder.set(column.getColumnFamily());
            Range colfamPrefixRange = Range.prefix(row, cfHolder);
            Key colfamPrefixStartKey = new Key(row, cfHolder);

            SortedMap<Key, Value> cfTailMap = rowKVs.tailMap(colfamPrefixStartKey);

            // Find the element
            if (cfTailMap.isEmpty()) {
                tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
            } else {
                HashMap<String, DataByteArray> tupleMap = new HashMap<String, DataByteArray>();

                // Build up a map for all the entries in this row that match
                // the colfam prefix
                for (Entry<Key, Value> entry : cfTailMap.entrySet()) {
                    if (colfamPrefixRange.contains(entry.getKey())) {
                        entry.getKey().getColumnFamily(cfHolder);
                        entry.getKey().getColumnQualifier(cqHolder);
                        DataByteArray val = new DataByteArray(entry.getValue().get());

                        // Avoid adding an extra ':' when colqual is empty
                        if (0 == cqHolder.getLength()) {
                            tupleMap.put(cfHolder.toString(), val);
                        } else {
                            tupleMap.put(cfHolder.toString() + COLON + cqHolder.toString(), val);
                        }
                    } else {
                        break;
                    }
                }

                if (!tupleMap.isEmpty()) {
                    tuple.set(tupleOffset, tupleMap);
                }
            }

            break;
        case COLQUAL_PREFIX:
            cfHolder.set(column.getColumnFamily());
            cqHolder.set(column.getColumnQualifier());
            Range colqualPrefixRange = Range.prefix(row, cfHolder, cqHolder);
            Key colqualPrefixStartKey = new Key(row, cfHolder, cqHolder);

            SortedMap<Key, Value> cqTailMap = rowKVs.tailMap(colqualPrefixStartKey);
            if (cqTailMap.isEmpty()) {
                tuple.set(tupleOffset, EMPTY_DATA_BYTE_ARRAY);
            } else {
                HashMap<String, DataByteArray> tupleMap = new HashMap<String, DataByteArray>();

                // Build up a map for all the entries in this row that match
                // the colqual prefix
                for (Entry<Key, Value> entry : cqTailMap.entrySet()) {
                    if (colqualPrefixRange.contains(entry.getKey())) {
                        entry.getKey().getColumnFamily(cfHolder);
                        entry.getKey().getColumnQualifier(cqHolder);
                        DataByteArray val = new DataByteArray(entry.getValue().get());

                        // Avoid the extra ':' on empty colqual
                        if (0 == cqHolder.getLength()) {
                            tupleMap.put(cfHolder.toString(), val);
                        } else {
                            tupleMap.put(cfHolder.toString() + COLON + cqHolder.toString(), val);
                        }
                    } else {
                        break;
                    }
                }

                if (!tupleMap.isEmpty()) {
                    tuple.set(tupleOffset, tupleMap);
                }
            }

            break;
        default:
            break;
        }
    }

    return tuple;
}

From source file:accumulo.balancer.GroupBalancer.java

@Override
public void getAssignments(SortedMap<TServerInstance, TabletServerStatus> current,
        Map<KeyExtent, TServerInstance> unassigned, Map<KeyExtent, TServerInstance> assignments) {

    if (current.size() == 0) {
        return;/*from  www.  ja va 2s  . co  m*/
    }

    Function<KeyExtent, String> partitioner = getPartitioner();

    List<ComparablePair<String, KeyExtent>> tabletsByGroup = new ArrayList<>();
    for (Entry<KeyExtent, TServerInstance> entry : unassigned.entrySet()) {
        TServerInstance last = entry.getValue();
        if (last != null) {
            // Maintain locality
            String fakeSessionID = " ";
            TServerInstance simple = new TServerInstance(last.getLocation(), fakeSessionID);
            Iterator<TServerInstance> find = current.tailMap(simple).keySet().iterator();
            if (find.hasNext()) {
                TServerInstance tserver = find.next();
                if (tserver.host().equals(last.host())) {
                    assignments.put(entry.getKey(), tserver);
                    continue;
                }
            }
        }

        tabletsByGroup
                .add(new ComparablePair<String, KeyExtent>(partitioner.apply(entry.getKey()), entry.getKey()));
    }

    Collections.sort(tabletsByGroup);

    Iterator<TServerInstance> tserverIter = Iterators.cycle(current.keySet());
    for (ComparablePair<String, KeyExtent> pair : tabletsByGroup) {
        KeyExtent ke = pair.getSecond();
        assignments.put(ke, tserverIter.next());
    }

}

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

/**
 * This includes deleted writes as zero length byte arrays, be sure to strip them out.
 *//* w ww  .j  a  v a  2s  .c om*/
private SortedMap<Cell, byte[]> getLocalWritesForRange(String tableName, byte[] startRow, byte[] endRow) {
    SortedMap<Cell, byte[]> writes = getLocalWrites(tableName);
    if (startRow.length != 0) {
        writes = writes.tailMap(Cells.createSmallestCellForRow(startRow));
    }
    if (endRow.length != 0) {
        writes = writes.headMap(Cells.createSmallestCellForRow(endRow));
    }
    return writes;
}

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

/**
 * This will add any local writes for this row to the result map.
 * <p>/*from  w  w w . j a v a 2s  . c o m*/
 * If an empty value was written as a delete, this will also be included in the map.
 */
private void extractLocalWritesForRow(@Output Map<Cell, byte[]> result, SortedMap<Cell, byte[]> writes,
        byte[] row) {
    Cell lowCell = Cells.createSmallestCellForRow(row);
    Iterator<Entry<Cell, byte[]>> it = writes.tailMap(lowCell).entrySet().iterator();
    while (it.hasNext()) {
        Entry<Cell, byte[]> e = it.next();
        Cell cell = e.getKey();
        if (!Arrays.equals(row, cell.getRowName())) {
            break;
        }
        result.put(cell, e.getValue());
    }
}

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

/**
 * Test method for 'java.util.SortedMap.tailMap(Object, Object)'.
 *
 * @see java.util.SortedMap#tailMap(Object)
 *///from ww w.jav  a2 s . com
public void testTailMap_throwsNullPointerException() {
    SortedMap<K, V> sortedMap = createNavigableMap();
    try {
        sortedMap.tailMap(null);
        assertTrue(useNullKey());
    } catch (NullPointerException e) {
        assertFalse(useNullKey());
    }
}