Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

map

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

like image 307
Edd Avatar asked Jan 25 '12 17:01

Edd


People also ask

How do I tell if a map key contains a String?

You can loop over the keys of the map and check if they are in the string: String str = "Java is cool!"; Map<String, ...> map = ...; for (String key : map. keySet()) { if (str. contains(key)) { ... } }

How do you know if a map contains a key-value pair?

Check if the key exists in the HashMap or not using HashMap. containsKey() method. If the key exists, set the flag as true. The flag value, contains the result.

Can we use String as key in map?

String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.

Which method will test if a key exists in a map object?

To check if a key exists in a Map , call the has() method on the Map , passing it the name of the key as a parameter. The has method returns true if the specified key exists in the Map , otherwise it returns false .


2 Answers

This can be done with a standard SortedMap:

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

Unsorted maps (e.g. HashMap) don't intrinsically support prefix lookups, so for those you'll have to iterate over all keys.

like image 63
NPE Avatar answered Oct 17 '22 16:10

NPE


From the map, you can get a Set of Keys, and in case they are String, you can iterate over the elements of the Set and check for startsWith("abc")

like image 26
Adel Boutros Avatar answered Oct 17 '22 17:10

Adel Boutros