3

i want to convert a ConcurrentHashMap to a TreeMap.Can i do that?

3
  • 1
    I'm curious as to why. If this is for performance reasons (I might be out of date, but I believe there was at one time some performance overhead with the Concurrent collections), have you profiled to make sure that this is your bottleneck? Commented Aug 31, 2010 at 19:20
  • 1
    You'll have to more specific. A ConcurrentHashMap is a threadsafe unordered map implementation. A TreeMap is a non-threadsafe ordered map implementation. Show a code snippet to illustrate what you mean by "convert".
    – Mike Q
    Commented Aug 31, 2010 at 19:20
  • Please expand your question: Is this a one time conversion in order to access the contents in order one time, or a global code change to get sorted access multiple times?
    – Darron
    Commented Aug 31, 2010 at 19:43

3 Answers 3

6

If you need a Sorted ConcurrentMap look at ConcurrentSkipListMap. Considering its complexity it is both non blocking and fast. To be more specific:

This class implements a concurrent variant of SkipLists providing expected average log(n) time cost for the
containsKey, get, put and remove operations and their variants.

5

A ConcurrentHashMap is still a Map. So you can create a new TreeMap like this:

ConcurrentHashMap myMap;
...
TreeMap myTreeMap = new TreeMap( myMap );
1
  • +1. Worth mentioning that the constructor runs in n log(n) time
    – Noel M
    Commented Aug 31, 2010 at 19:28
2

First I would like to point you. you should learn to read the java SDK documentation.

Like Tangens said, and the TreeMap API:

ConcurrentHashMAp myMap;
new TreeMap(myMap);

"Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally"

SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

Not the answer you're looking for? Browse other questions tagged or ask your own question.