Java – how to check whether a key in a map starts with a given string value

I am looking for a way, such as:

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

or

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

I wonder if anyone knows a simple way to do this

thank you

Solution

This can be done using the standard SortedMap:

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

Unordered maps (such as HashMap) do not support prefix lookup in essence, so for those maps where you have to iterate all keys

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>