简体   繁体   English

如何检查Map中的键是否以给定的String值开头

[英]How to check if a key in a Map starts with a given String value

I'm looking for a method like: 我正在寻找一种方法:

myMap.containsKeyStartingWith("abc"); // returns true if there's a key starting with "abc" e.g. "abcd"

or 要么

MapUtils.containsKeyStartingWith(myMap, "abc"); // same

I wondered if anyone knew of a simple way to do this 我想知道是否有人知道这样做的简单方法

Thanks 谢谢

This can be done with a standard SortedMap : 这可以使用标准的SortedMap

Map<String,V> tailMap = myMap.tailMap(prefix);
boolean result = (!tailMap.isEmpty() && tailMap.firstKey().startsWith(prefix));

Unsorted maps (eg HashMap ) don't intrinsically support prefix lookups, so for those you'll have to iterate over all keys. 未排序的映射(例如HashMap )本质上不支持前缀查找,因此对于那些您必须迭代所有键。

从地图中,您可以获得一组键,如果它们是String,您可以迭代Set的元素并检查startsWith("abc")

To build on Adel Boutros answer/comment about the efficiency of iterating keys, you could encapsulate key iteration in a Map subclass or decorator. 要建立在Adel Boutros上关于迭代键效率的答案/评论,您可以将关键迭代封装在Map子类或装饰器中。

Extending HashMap would give you a class to put the method in and keep map-specific code out of your method, so lowering complexity and making the code more natural to read. 扩展HashMap会为您提供一个类,可以将方法放在您的方法中,并保留特定于地图的代码,从而降低复杂性并使代码更自然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM