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

这篇博客介绍了如何利用Java中的NavigableMap,特别是TreeMap,来实现高效的按前缀查找操作。通过调用subMap方法,可以在O(lg(N))的时间复杂度下获取所有以特定前缀开头的键值对。示例代码展示了如何查找并打印出以特定字符串为前缀的所有条目。
摘要由CSDN通过智能技术生成

小编典典

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值