首先,我建议重新检查您的要求。 Character.MAX_VALUE
是U + FFFF,它不是一个有效的Unicode字符,永远不会;所以我想不出你需要支持它的一个很好的理由。
但是,如果这个要求有一个很好的理由,那么你需要“增加”你的前缀来计算最大的字符串,它大于以你的前缀开头的所有字符串。例如,给定"city"
,则需要"citz"
。你可以做如下:
/**
* @param prefix
* @return The least string that's greater than all strings starting with
* prefix, if one exists. Otherwise, returns Optional.empty().
* (Specifically, returns Optional.empty() if the prefix is the
* empty string, or is just a sequence of Character.MAX_VALUE-s.)
*/
private static Optional<String> incrementPrefix(final String prefix) {
final StringBuilder sb = new StringBuilder(prefix);
// remove any trailing occurrences of Character.MAX_VALUE:
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == Character.MAX_VALUE) {
sb.setLength(sb.length() - 1);
}
// if the prefix is empty, then there's no upper bound:
if (sb.length() == 0) {
return Optional.empty();
}
// otherwise, increment the last character and return the result:
sb.setCharAt(sb.length() - 1, (char) (sb.charAt(sb.length() - 1) + 1));
return Optional.of(sb.toString());
}
要使用它,你需要使用subSet
当上述方法返回一个字符串,并tailSet
当它没有返回值:
/**
* @param allElements - a SortedSet of strings. This set must use the
* natural string ordering; otherwise this method
* may not behave as intended.
* @param prefix
* @return The subset of allElements containing the strings that start
* with prefix.
*/
private static SortedSet<String> getElementsWithPrefix(
final SortedSet<String> allElements, final String prefix) {
final Optional<String> endpoint = incrementPrefix(prefix);
if (endpoint.isPresent()) {
return allElements.subSet(prefix, endpoint.get());
} else {
return allElements.tailSet(prefix);
}
}
在看到它在行动:http://ideone.com/YvO4b3。
cityNames是什么类型的?您可以发布[最小,完整和可验证的示例](https://stackoverflow.com/help/mcve)? – tnas