Example usage for java.util SortedMap headMap

List of usage examples for java.util SortedMap headMap

Introduction

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

Prototype

SortedMap<K, V> headMap(K toKey);

Source Link

Document

Returns a view of the portion of this map whose keys are strictly less than toKey .

Usage

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

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

    Map<K, V> head = map.headMap(keys[3]);
    assertEquals(3, head.size());
    assertTrue(head.containsKey(keys[0]));
    assertTrue(head.containsValue(values[1]));
    assertTrue(head.containsKey(keys[2]));

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

        SortedMap<K, V> submap = map.headMap(null);
        assertEquals(0, submap.size());

        Set<K> keySet = submap.keySet();
        assertEquals(0, keySet.size());

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

        Collection<V> valueCollection = submap.values();
        assertEquals(0, valueCollection.size());

        map.remove(null);
    }

    SortedMap<K, V> submap = map.headMap(getLessThanMinimumKey());
    assertEquals(submap.size(), 0);
    assertTrue(submap.isEmpty());
    try {
        submap.firstKey();
        fail("NoSuchElementException should be thrown");
    } catch (NoSuchElementException expected) {
    }

    try {
        submap.lastKey();
        fail("NoSuchElementException should be thrown");
    } catch (NoSuchElementException expected) {
    }

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

From source file:net.sourceforge.subsonic.service.SonosService.java

@Override
public ReorderContainerResult reorderContainer(String id, String from, int to, String updateId) {
    if (id.startsWith(ID_PLAYLIST_PREFIX)) {
        int playlistId = Integer.parseInt(id.replace(ID_PLAYLIST_PREFIX, ""));
        Playlist playlist = playlistService.getPlaylist(playlistId);
        if (playlist != null && playlist.getUsername().equals(getUsername())) {

            SortedMap<Integer, MediaFile> indexToSong = new ConcurrentSkipListMap<Integer, MediaFile>();
            List<MediaFile> songs = playlistService.getFilesInPlaylist(playlistId);
            for (int i = 0; i < songs.size(); i++) {
                indexToSong.put(i, songs.get(i));
            }//from  w ww . j av  a2 s .co m

            List<MediaFile> movedSongs = new ArrayList<MediaFile>();
            for (Integer i : parsePlaylistIndices(from)) {
                movedSongs.add(indexToSong.remove(i));
            }

            List<MediaFile> updatedSongs = new ArrayList<MediaFile>();
            updatedSongs.addAll(indexToSong.headMap(to).values());
            updatedSongs.addAll(movedSongs);
            updatedSongs.addAll(indexToSong.tailMap(to).values());

            playlistService.setFilesInPlaylist(playlistId, updatedSongs);
        }
    }
    return new ReorderContainerResult();
}

From source file:org.apache.accumulo.server.tabletserver.Tablet.java

private SplitRowSpec findSplitRow(Collection<FileRef> files) {

    // never split the root tablet
    // check if we already decided that we can never split
    // check to see if we're big enough to split

    long splitThreshold = acuTableConf.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD);
    if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) {
        return null;
    }/*www.  j ava2 s.c o m*/

    // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred.
    if (sawBigRow) {
        if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime
                || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) {
            // a minor compaction or map file import has occurred... check again
            sawBigRow = false;
        } else {
            // nothing changed, do not split
            return null;
        }
    }

    SortedMap<Double, Key> keys = null;

    try {
        // we should make .25 below configurable
        keys = FileUtil.findMidPoint(fs, tabletServer.getSystemConfiguration(), extent.getPrevEndRow(),
                extent.getEndRow(), files, .25);
    } catch (IOException e) {
        log.error("Failed to find midpoint " + e.getMessage());
        return null;
    }

    // check to see if one row takes up most of the tablet, in which case we can not split
    try {

        Text lastRow;
        if (extent.getEndRow() == null) {
            Key lastKey = (Key) FileUtil.findLastKey(fs, tabletServer.getSystemConfiguration(), files);
            lastRow = lastKey.getRow();
        } else {
            lastRow = extent.getEndRow();
        }

        // check to see that the midPoint is not equal to the end key
        if (keys.get(.5).compareRow(lastRow) == 0) {
            if (keys.firstKey() < .5) {
                Key candidate = keys.get(keys.firstKey());
                if (candidate.compareRow(lastRow) != 0) {
                    // we should use this ratio in split size estimations
                    if (log.isTraceEnabled())
                        log.trace(String.format(
                                "Splitting at %6.2f instead of .5, row at .5 is same as end row%n",
                                keys.firstKey()));
                    return new SplitRowSpec(keys.firstKey(), candidate.getRow());
                }

            }

            log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow);

            sawBigRow = true;
            timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime;
            timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime;

            return null;
        }
        Key mid = keys.get(.5);
        Text text = (mid == null) ? null : mid.getRow();
        SortedMap<Double, Key> firstHalf = keys.headMap(.5);
        if (firstHalf.size() > 0) {
            Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow();
            Text shorter = new Text();
            int trunc = longestCommonLength(text, beforeMid);
            shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1));
            text = shorter;
        }
        return new SplitRowSpec(.5, text);
    } catch (IOException e) {
        // don't split now, but check again later
        log.error("Failed to find lastkey " + e.getMessage());
        return null;
    }
}

From source file:org.apache.accumulo.tserver.tablet.Tablet.java

private SplitRowSpec findSplitRow(Collection<FileRef> files) {

    // never split the root tablet
    // check if we already decided that we can never split
    // check to see if we're big enough to split

    long splitThreshold = tableConfiguration.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD);
    long maxEndRow = tableConfiguration.getMemoryInBytes(Property.TABLE_MAX_END_ROW_SIZE);

    if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) {
        return null;
    }/*from w  ww. j av  a  2  s  . c  o m*/

    // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred.
    if (sawBigRow) {
        if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime
                || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) {
            // a minor compaction or map file import has occurred... check again
            sawBigRow = false;
        } else {
            // nothing changed, do not split
            return null;
        }
    }

    SortedMap<Double, Key> keys = null;

    try {
        // we should make .25 below configurable
        keys = FileUtil.findMidPoint(getTabletServer().getFileSystem(), getTabletServer().getConfiguration(),
                extent.getPrevEndRow(), extent.getEndRow(), FileUtil.toPathStrings(files), .25);
    } catch (IOException e) {
        log.error("Failed to find midpoint " + e.getMessage());
        return null;
    }

    // check to see if one row takes up most of the tablet, in which case we can not split
    try {

        Text lastRow;
        if (extent.getEndRow() == null) {
            Key lastKey = (Key) FileUtil.findLastKey(getTabletServer().getFileSystem(),
                    getTabletServer().getConfiguration(), files);
            lastRow = lastKey.getRow();
        } else {
            lastRow = extent.getEndRow();
        }

        // We expect to get a midPoint for this set of files. If we don't get one, we have a problem.
        final Key mid = keys.get(.5);
        if (null == mid) {
            throw new IllegalStateException("Could not determine midpoint for files");
        }

        // check to see that the midPoint is not equal to the end key
        if (mid.compareRow(lastRow) == 0) {
            if (keys.firstKey() < .5) {
                Key candidate = keys.get(keys.firstKey());
                if (candidate.getLength() > maxEndRow) {
                    log.warn("Cannot split tablet " + extent + ", selected split point too long.  Length :  "
                            + candidate.getLength());

                    sawBigRow = true;
                    timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime;
                    timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime;

                    return null;
                }
                if (candidate.compareRow(lastRow) != 0) {
                    // we should use this ratio in split size estimations
                    if (log.isTraceEnabled())
                        log.trace(String.format(
                                "Splitting at %6.2f instead of .5, row at .5 is same as end row%n",
                                keys.firstKey()));
                    return new SplitRowSpec(keys.firstKey(), candidate.getRow());
                }

            }

            log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow);

            sawBigRow = true;
            timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime;
            timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime;

            return null;
        }

        Text text = mid.getRow();
        SortedMap<Double, Key> firstHalf = keys.headMap(.5);
        if (firstHalf.size() > 0) {
            Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow();
            Text shorter = new Text();
            int trunc = longestCommonLength(text, beforeMid);
            shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1));
            text = shorter;
        }

        if (text.getLength() > maxEndRow) {
            log.warn("Cannot split tablet " + extent + ", selected split point too long.  Length :  "
                    + text.getLength());

            sawBigRow = true;
            timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime;
            timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime;

            return null;
        }

        return new SplitRowSpec(.5, text);
    } catch (IOException e) {
        // don't split now, but check again later
        log.error("Failed to find lastkey " + e.getMessage());
        return null;
    }

}

From source file:org.apache.accumulo.tserver.Tablet.java

private SplitRowSpec findSplitRow(Collection<FileRef> files) {

    // never split the root tablet
    // check if we already decided that we can never split
    // check to see if we're big enough to split

    long splitThreshold = acuTableConf.getMemoryInBytes(Property.TABLE_SPLIT_THRESHOLD);
    if (extent.isRootTablet() || estimateTabletSize() <= splitThreshold) {
        return null;
    }//from  ww w  .  ja  va2 s .  co m

    // have seen a big row before, do not bother checking unless a minor compaction or map file import has occurred.
    if (sawBigRow) {
        if (timeOfLastMinCWhenBigFreakinRowWasSeen != lastMinorCompactionFinishTime
                || timeOfLastImportWhenBigFreakinRowWasSeen != lastMapFileImportTime) {
            // a minor compaction or map file import has occurred... check again
            sawBigRow = false;
        } else {
            // nothing changed, do not split
            return null;
        }
    }

    SortedMap<Double, Key> keys = null;

    try {
        // we should make .25 below configurable
        keys = FileUtil.findMidPoint(fs, tabletServer.getSystemConfiguration(), extent.getPrevEndRow(),
                extent.getEndRow(), FileUtil.toPathStrings(files), .25);
    } catch (IOException e) {
        log.error("Failed to find midpoint " + e.getMessage());
        return null;
    }

    // check to see if one row takes up most of the tablet, in which case we can not split
    try {

        Text lastRow;
        if (extent.getEndRow() == null) {
            Key lastKey = (Key) FileUtil.findLastKey(fs, tabletServer.getSystemConfiguration(), files);
            lastRow = lastKey.getRow();
        } else {
            lastRow = extent.getEndRow();
        }

        // check to see that the midPoint is not equal to the end key
        if (keys.get(.5).compareRow(lastRow) == 0) {
            if (keys.firstKey() < .5) {
                Key candidate = keys.get(keys.firstKey());
                if (candidate.compareRow(lastRow) != 0) {
                    // we should use this ratio in split size estimations
                    if (log.isTraceEnabled())
                        log.trace(String.format(
                                "Splitting at %6.2f instead of .5, row at .5 is same as end row%n",
                                keys.firstKey()));
                    return new SplitRowSpec(keys.firstKey(), candidate.getRow());
                }

            }

            log.warn("Cannot split tablet " + extent + " it contains a big row : " + lastRow);

            sawBigRow = true;
            timeOfLastMinCWhenBigFreakinRowWasSeen = lastMinorCompactionFinishTime;
            timeOfLastImportWhenBigFreakinRowWasSeen = lastMapFileImportTime;

            return null;
        }
        Key mid = keys.get(.5);
        Text text = (mid == null) ? null : mid.getRow();
        SortedMap<Double, Key> firstHalf = keys.headMap(.5);
        if (firstHalf.size() > 0) {
            Text beforeMid = firstHalf.get(firstHalf.lastKey()).getRow();
            Text shorter = new Text();
            int trunc = longestCommonLength(text, beforeMid);
            shorter.set(text.getBytes(), 0, Math.min(text.getLength(), trunc + 1));
            text = shorter;
        }
        return new SplitRowSpec(.5, text);
    } catch (IOException e) {
        // don't split now, but check again later
        log.error("Failed to find lastkey " + e.getMessage());
        return null;
    }
}

From source file:org.apache.hadoop.hbase.client.TestClientNoCluster.java

static GetResponse doMetaGetResponse(final SortedMap<byte[], Pair<HRegionInfo, ServerName>> meta,
        final GetRequest request) {
    ClientProtos.Result.Builder resultBuilder = ClientProtos.Result.newBuilder();
    ByteString row = request.getGet().getRow();
    Pair<HRegionInfo, ServerName> p = meta.get(row.toByteArray());
    if (p == null) {
        if (request.getGet().getClosestRowBefore()) {
            byte[] bytes = row.toByteArray();
            SortedMap<byte[], Pair<HRegionInfo, ServerName>> head = bytes != null ? meta.headMap(bytes) : meta;
            p = head == null ? null : head.get(head.lastKey());
        }//  w ww  . j  a  va 2 s  . c  o  m
    }
    if (p != null) {
        resultBuilder.addCell(getRegionInfo(row, p.getFirst()));
        resultBuilder.addCell(getServer(row, p.getSecond()));
    }
    resultBuilder.addCell(getStartCode(row));
    GetResponse.Builder builder = GetResponse.newBuilder();
    builder.setResult(resultBuilder.build());
    return builder.build();
}

From source file:org.archive.util.PrefixFinder.java

public static List<String> findKeys(SortedMap<String, ?> map, String input) {
    LinkedList<String> result = new LinkedList<String>();
    map = headMapInclusive(map, input);/*w ww  .ja  v  a 2  s .co  m*/
    for (String last = last(map); last != null; last = last(map)) {
        if (input.startsWith(last)) {
            result.push(last);
            map = map.headMap(last);
        } else {
            // Find the longest common prefix.
            int p = StringUtils.indexOfDifference(input, last);
            if (p <= 0) {
                return result;
            }
            last = input.substring(0, p);
            map = headMapInclusive(map, last);
        }
    }
    return result;
}

From source file:org.archive.util.PrefixFinder.java

private static SortedMap<String, ?> headMapInclusive(SortedMap<String, ?> map, String input) {
    // use NavigableMap inclusive version if available
    if (map instanceof NavigableMap) {
        return ((NavigableMap<String, ?>) map).headMap(input, true);
    }/*from w  w w .  j  a v a  2 s . com*/
    // use StoredSortedMap inclusive version if available
    if (map instanceof StoredSortedMap) {
        return ((StoredSortedMap<String, ?>) map).headMap(input, true);
    }
    // Use synthetic "one above" trick
    // NOTE: because '\0' sorts in the middle in "java modified UTF-8",
    // used in the Stored* class StringBindings, this trick won't work
    // there
    return map.headMap(input + '\0');
}

From source file:org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.java

public static <S> S forStationAdjacent(final SortedMap<BigDecimal, S> stationIndex, final BigDecimal station,
        final boolean upstream) {
    final BigDecimal pred = NumberUtils.decrement(station);
    final BigDecimal succ = NumberUtils.increment(station);

    if (upstream) {
        final SortedMap<BigDecimal, ? extends Object> successors = stationIndex.tailMap(succ);
        if (!successors.isEmpty())
            return stationIndex.get(successors.firstKey());
    } else {/*from w  w  w .j ava2s .  co m*/

        final SortedMap<BigDecimal, ? extends Object> predecessors = stationIndex.headMap(pred);
        if (!predecessors.isEmpty())
            return stationIndex.get(predecessors.lastKey());
    }

    return null;
}

From source file:org.languagetool.rules.spelling.suggestions.SuggestionsChanges.java

private List<Map<String, Object>> gridsearch(SortedMap<String, List<Object>> grid,
        List<Map<String, Object>> current) {
    if (grid.isEmpty()) { // recursion exit
        return current;
    }//from   www  . j ava  2  s .c om

    String name = grid.lastKey();
    List<Object> params = grid.get(name);
    List<Map<String, Object>> result = new LinkedList<>();

    if (current.isEmpty()) {
        for (Object value : params) {
            result.add(Collections.singletonMap(name, value));
        }
    } else {
        for (Map<String, Object> entry : current) {
            for (Object value : params) {
                Map<String, Object> modified = new HashMap<>(entry);
                modified.put(name, value);
                result.add(modified);
            }
        }
    }

    return gridsearch(grid.headMap(name), result);
}