Reputation: 3784
I am looking for a container that would basically work like HashMap
where I could put and get any of the entries in O(1) time. I also want to be able to iterate through but I want the order to be sorted by values. So neither TreeMap
nor LinkedHashMap
would work for me. I found the example below:
SortedSet<Map.Entry<String, Double>> sortedSet = new TreeSet<Map.Entry<String, Double>>(
new Comparator<Map.Entry<String, Double>>() {
@Override
public int compare(Map.Entry<String, Double> e1,
Map.Entry<String, Double> e2) {
return e1.getValue().compareTo(e2.getValue());
}});
The problem is SortedSet
doesn't have any get method to get entries.
I will be using this collection in a place where I will be adding entries but in case of already existing entry, the value(double) will be updated and then sorted again by using the comparator(which compares values as mentioned above). What can I use for my needs?
Upvotes: 0
Views: 2399
Reputation: 718758
There is no such data structure in the Java class libraries.
But you could create one that is a wrapper for a private HashMap and a private TreeMap with the same set of key/value pairs.
This gives a data structure that has get
complexity of O(1)
like a regular HashMap
(but not put
or other update operations), and a key Set and entry Set which can be iterated in key order ... as requested in the original version of this Question.
Here is a start for you:
public class HybridMap<K,V> implements Map<K,V> {
private HashMap<K,V> hashmap = ...
private TreeMap<K,V> treemap = ...
@Override V get(K key) {
return hashmap.get(key);
}
@Override void (K key, V value) {
hashmap.put(key, value);
treemap.put(key, value);
}
// etcetera
}
Obviously, I've only implemented some of the (easy) methods.
If you want to be able to iterate the entries in value order (rather than key order), once again there is no such data structure in the Java class libraries.
In this case, wrapping a HashMap
and TreeMap
is going to be very complicated if you need the resulting Map
to conform fully to the API contract.
So I suggest that you just use a HashMap and TreeSet of the key/value pairs ... and manually keep them in step.
Upvotes: 1