栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

如果您使用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}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446677.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号