Fastest way to get all values from a Map where the key starts with a certain expression

前端 未结 5 1995
不思量自难忘°
不思量自难忘° 2020-12-15 05:58

Consider you have a map myMap.

Given the expression \"some.string.*\", I have to retrieve all the values from m

5条回答
  •  悲哀的现实
    2020-12-15 06:32

    If you work with NavigableMap (e.g. TreeMap), you can use benefits of underlying tree data structure, and do something like this (with O(lg(N)) complexity):

    public SortedMap getByPrefix( 
            NavigableMap myMap, 
            String prefix ) {
        return myMap.subMap( prefix, prefix + Character.MAX_VALUE );
    }
    

    More expanded example:

    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 );
        }
    }
    

    Output is:

    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}
    

提交回复
热议问题