Search code examples
javasearchhashmap

HashMap<String, Integer> Search for part of an key?


I am currently using HashMap<String, Integer> which is filled with keys of type String which are all, let's say, 5 chars long. How can I search for an specific key of 4 chars or less, which is part and at the beginning of some other keys and get all hits as a collection of <Key, Value>?


Solution

  • Iterate is your only option unless you create a custom data structure:

    for (Entry<String, Integer> e : map.entrySet()) {
        if (e.getKey().startsWith("xxxx")) {
            //add to my result list
        }
    }
    

    If you need something more time efficient then you'd need an implementation of map where you are tracking these partial keys.