如何检查Map中的键是否以给定的String值开头

Edd*_*Edd 13 java string map

我正在寻找一种方法:

myMap.containsKeyStartingWith("abc"); // returns true if there's a key starting with "abc" e.g. "abcd"
Run Code Online (Sandbox Code Playgroud)

要么

MapUtils.containsKeyStartingWith(myMap, "abc"); // same
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人知道这样做的简单方法

谢谢

NPE*_*NPE 14

这可以使用标准来完成SortedMap:

Map<String,V> tailMap = myMap.tailMap(prefix);
boolean result = (!tailMap.isEmpty() && tailMap.firstKey().startsWith(prefix));
Run Code Online (Sandbox Code Playgroud)

未排序的映射(例如HashMap)本质上不支持前缀查找,因此对于那些您必须迭代所有键.

  • @Edd:或者,甚至更简单,`TreeMap <K,V> treeMap = new TreeMap <K,V>(hashMap);` (4认同)