I am looking for a collection to store key value pair, where value should be returned on the basis of key startswith
condition.
for e.g. for the given collection: (a,123) (ab,234) (abcd,5434)
If I do map.get(a)
it should give me array of {123,234,5434}
, similarly if I do map.get(ab)
it should give me {234,5434}
but not {123}
in this case.
So, it looks for all the values those have key with exact match or starts with.
Any suggestions? if there is something already available or if I can write something up?
Thanks!
You can do this with TreeMap<String,Integer>
using the tailMap
method, and iterating the result while the key matches the input:
TreeMap<String,Integer> map = new TreeMap<String,Integer>();
map.put("a", 123);
map.put("ab", 234);
map.put("abcd", 5434);
String myKey = "ab";
for (Map.Entry<String,Integer> e : map.tailMap(myKey).entrySet()) {
if (!e.getKey().startsWith(myKey)) {
break;
}
System.out.println(e.getValue());
}
Demo.
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