Java get values from LinkedHashMap with key part
I have the following key value system (HashMap) where the String will be the same as "2014/12/06".
LinkedHashMap<String, Value>
So I can get an item knowing the key, but what I am looking for is a method to get a list of values that a key matches partially, I mean how could I get all 2014 values ?.
I would like to avoid solutions like: check every item in the list, brute force or the like.
thank.
source to share
Apart from doing brute-force iteration over all keys, I can imagine two options:
-
Use a TreeMap, which is where the keys are sorted, so you can find the first key which is> = "2014/01/01" (with
map.getCeilingEntry("2014/01/01")
) and navigate all the keys from there. -
Use a map hierarchy - i.e.
Map<String,Map<String,Value>>
... The key on the external card will be a year. The key on the internal card will be the full date.
source to share
If you only want to get the elements using the first part of the key, then you want to TreeMap
, not LinkedHashMap
. A is LinkedHashMap
sorted according to the insertion order, which is inappropriate for this, but TreeMap
sorted according to the natural ordering, or with Comparator
which you supply. This means that you can find the first entry starting at 2014
efficiently (during log time) and then iterate until you get to the first that doesn't match.
If you want to be able to match any part of a key, you need a completely different solution beyond the simple one Map
. You will need to search for full text search and indexing. You can try something like Lucene.
source to share
You can refine the hash function for your values so that values with a similar year are a hash around similar prefix hashes. This would be inefficient (possibly poor distribution of hashes), not in the spirit of HashMaps. Use other map implementations like TreeMaps that preserve the order of your choice.
source to share