天天看点

java map prefix_从键以特定表达式开头的Map中获取所有值的最快方法

小编典典

如果您使用NavigableMap(例如TreeMap),则可以利用基础树数据结构的好处,并执行以下操作(非常O(lg(N))复杂):

public SortedMap getByPrefix(

NavigableMap 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 myMap = new TreeMap();

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 getByPrefix(

NavigableMap 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}

2020-10-25