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>
?
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.
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.
Apache Commons collection classes can implement multiple values under same key.
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.
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.
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
You cannot do this via HashMap
, you should write your own implementation for Map
for implementing string length based searching in a map.
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