Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java key-value pair with key lookup as "startswith"

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!

like image 871
Dadu Avatar asked May 19 '15 15:05

Dadu


1 Answers

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.

like image 85
Sergey Kalinichenko Avatar answered Oct 10 '22 05:10

Sergey Kalinichenko