Reputation:
What is the best way to implement a three item hashMap? For example, I would like to use a regular String key , but have it map to two different objects. The idea is like having a list of lists, except that the first item is a key.
I am trying to avoid iterating through the list ( so the behavior is like a hashmap ). Would you agree the only way is to build a new Class? It seems a "HashMap3" object ( with methods of get1( key ) & get2( key ) ) would be useful. I am unsure of how to set this up myself.
How can I create the collection?
Upvotes: 1
Views: 2815
Reputation: 31012
I agree with Eddie, and just had a similar problem only with many values, not two. I wanted a Java ConcurrentHashMap to hold a cache XML of documents being fetched from a web service, and I needed to record various pieces of information alongside the XML to support the cache's eviction strategies (eg, Least Recently Used, Least Frequently Used).
The solution was just to define a class of object that holds those items. I used a private nested class inside of my Cache class, something like this:
private static class CacheEntry
{
private String uri; // Key
private String fetched_xml; // The XML document (main value)
private long put_time;
private long expires_time;
private long size;
private long hits;
private long last_used_time;
}
The ConcurrentHashMap was keyed on the URI and looked like this:
private final Map<String, CacheEntry> cache;
[...]
cache = new ConcurrentHashMap<String, CacheEntry>(100, 0.75f, 3);
This code adds a new XML document to the cache:
CacheEntry value = new CacheEntry();
value.fetched_xml(fetched_xml);
value.uri = uri;
value.put_time = System.currentTimeMillis();
value.expires_time = representation.getExpirationDate().getTime();
value.size = bytes_fetched;
value.hits = 0;
value.last_used_time = 0;
cache.put(uri, value);
Edit: Should you need to Map a key to a List of n Objects in Java, you can put those objects in a java.util.collections.ArrayList and use the ArrayList as the Map value.
Upvotes: 0
Reputation: 24936
Look at google-collections Multimap
A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
Upvotes: 0
Reputation: 54421
If the key will always map to exactly two Objects, then the easiest way to do this is to make a Pair
class that exists only to hold the two objects. Then you use your String as the key and the Pair
instance as the value. However, if the key can map to arbitrarily many Objects, then IMO the best way to do this is to have the value stored in the Map
be a Collection
of some sort.
Upvotes: 4