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
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)) { ... } }
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.
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.
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 .
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With