从键中以某个表达式开始的Map获取所有值的最快方法 [英] Fastest way to get all values from a Map where the key starts with a certain expression
问题描述
考虑你有地图< String,Object> myMap
。
鉴于表达式some.string。*
,我有检索 myMap
中的所有值,其键以此表达式开头。
Given the expression "some.string.*"
, I have to retrieve all the values from myMap
whose keys starts with this expression.
我试图避免 for循环
s因为 myMap
将被赋予一组表达式,而不仅仅是一个表达式并使用 for循环每个表达式的code>变得很麻烦。
I am trying to avoid for loop
s because myMap
will be given a set of expressions not only one and using for loop
for each expression becomes cumbersome performance wise.
最快的方法是什么?
推荐答案
如果您使用 NavigableMap (例如 TreeMap ),您可以使用底层树数据结构的好处,并执行类似的操作(使用 O(lg(N))
复杂度):
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<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}
这篇关于从键中以某个表达式开始的Map获取所有值的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!