Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>?

like image 687
VoidStar Avatar asked May 21 '13 07:05

VoidStar


People also ask

How does HashMap check duplicate key?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Can we use integer as key in HashMap?

Java HashMap Example In this example, we are storing Integer as the key and String as the value, so we are using HashMap<Integer,String> as the type. The put() method inserts the elements in the map. To get the key and value elements, we should call the getKey() and getValue() methods.

Can we have multiple values for same key in HashMap?

Apache Commons collection classes can implement multiple values under same key.

How HashMap store duplicate values?

Let's see how to store our multiple values into an ArrayList, which retains duplicates: MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>(); map. put("key1", "value1"); map. put("key1", "value2"); map.


3 Answers

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.

like image 184
cyborg Avatar answered Oct 31 '22 16:10

cyborg


It seems like a use case for TreeMap rather than HashMap. The difference is that TreeMap preserves order. So you can find your partial match much quicker. You don't have to go through the whole map.

Check this question Partial search in HashMap

like image 45
Ondrej Bozek Avatar answered Oct 31 '22 14:10

Ondrej Bozek


You cannot do this via HashMap, you should write your own implementation for Map for implementing string length based searching in a map.

like image 41
harsh Avatar answered Oct 31 '22 16:10

harsh