Is there any way to create a thread-safe implementation of Map
that maintains it's entries sorted by value? I know I can create a thread-safe Map
like this
ConcurrentMap<String, Double> rankings = new ConcurrentHashMap<String, Double>();
And I can then get the entries sorted by value by passing it to a utility method like this:
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
But what I'm looking for is a thread-safe Map
that maintains the entries sorted by value, so that I don't have to call a method such as the above after every insertion/removal in order to keep the entries sorted by value. I guess I'm looking for an implementation that combines the behavior of ConcurrentHashMap
and LinkedHashMap
, but haven't found one yet.
ConcurrentSkipListMap almost provides what I want, but it only seems to support sorting by key value.