Example usage for java.util SortedMap comparator

List of usage examples for java.util SortedMap comparator

Introduction

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

Prototype

Comparator<? super K> comparator();

Source Link

Document

Returns the comparator used to order the keys in this map, or null if this map uses the Comparable natural ordering of its keys.

Usage

From source file:org.nuclos.common2.StringUtils.java

/**
 * Returns a living view of the given map containing all strings that starts with the given
 * prefix (including the prefix string itself). The view is backed by the original map.
 * <p>//from   w w  w.  j a v  a 2s.  c  om
 * Note: This method uses {@link SortedMap#subMap(Object, Object)} internally and works
 * <em>only</em> for sorted string maps with natural (lexiographic) ordering!
 */
public static <V> SortedMap<String, V> submapWithPrefix(SortedMap<String, V> map, String prefix) {
    if (map.comparator() != null)
        throw new IllegalArgumentException("only natural (lexiographic) ordering supported");
    int length = prefix.length();
    if (length == 0)
        return map;
    // create a string lhs which is the _least higher string_ for the prefix, i.e.
    // there is no other string value between any prefixed string and lhs w.r.t ordering.
    StringBuilder lhs = new StringBuilder(prefix);
    char ch = lhs.charAt(length - 1);
    lhs.setCharAt(length - 1, (char) (ch + 1));
    return map.subMap(prefix, lhs.toString());
}