Three HashMap elements without internal iteration
What's the best way to implement a 3-element hashmap? For example, I would like to use a regular String key, but map it to two different objects. The idea is similar to a list of lists, except that the first item is the key.
I am trying to avoid repeating the list (so the behavior is like a hashmap). Do you agree that the only way is to create a new class? It seems that the "HashMap3" object (with methods get1 (key) and get2 (key)) will be useful. I'm not sure how to do this myself.
How do I create a collection?
If the key will always map to exactly two objects, then the easiest way to do this is to create a class Pair
that only exists to store two objects. Then you use your string as key and instance Pair
as value. However, if a key can display an arbitrary number of objects, then IMO the best way to do it is to have the value stored in Map
as a Collection
.
a source to share
I agree with Eddie and I had a similar problem with only many values, not two. I wanted a Java ConcurrentHashMap to store a cache of XML documents received from a web service, and I needed to write various pieces of information along with the XML to support cache-off strategies (e.g. least used recently, least used).
The solution was only to define the class of the object that contains these elements. I used a private nested class inside 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 injected into 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: If you need to map a key to a list of n objects in Java, you can put those objects in java.util.collections.ArrayList and use ArrayList as the map value.
a source to share