如果您使用NavigableMap(例如TreeMap),则可以利用基础树数据结构的好处,并执行以下操作(非常
O(lg(N))复杂):
public SortedMap<String, Object> getByPrefix( NavigableMap<String, Object> myMap, String prefix ) { return myMap.subMap( prefix, prefix + Character.MAX_VALUE );}更扩展的示例:
import java.util.NavigableMap;import java.util.SortedMap;import java.util.TreeMap;public class Test { public static void main( String[] args ) { TreeMap<String, Object> myMap = new TreeMap<String, Object>(); myMap.put( "111-hello", null ); myMap.put( "111-world", null ); myMap.put( "111-test", null ); myMap.put( "111-java", null ); myMap.put( "123-one", null ); myMap.put( "123-two", null ); myMap.put( "123--three", null ); myMap.put( "123--four", null ); myMap.put( "125-hello", null ); myMap.put( "125--world", null ); System.out.println( "111 t" + getByPrefix( myMap, "111" ) ); System.out.println( "123 t" + getByPrefix( myMap, "123" ) ); System.out.println( "123-- t" + getByPrefix( myMap, "123--" ) ); System.out.println( "12 t" + getByPrefix( myMap, "12" ) ); } private static SortedMap<String, Object> getByPrefix( NavigableMap<String, Object> myMap, String prefix ) { return myMap.subMap( prefix, prefix + Character.MAX_VALUE ); }}输出为:
111 {111-hello=null, 111-java=null, 111-test=null, 111-world=null}123 {123--four=null, 123--three=null, 123-one=null, 123-two=null}123-- {123--four=null, 123--three=null}12 {123--four=null, 123--three=null, 123-one=null, 123-two=null, 125--world=null, 125-hello=null}


