0

I have a basic tree/algorithm question for Java:

Say I am constructing a new TreeMap:

TreeMap<KeyType,ValType> myTreeMap = new TreeMap<>();

And I also have an existing array of data that is already in Comparison order:

KeyType myArray[] = new KeyType[]{.......};

Is there a way to populate the TreeMap with this data in O(n) time? I.e., is this the most efficient method:

for (int i = 0; i < myArray.length; i++){
    myTreeMap.put(myArray[i],"blah");
}

Or is there a way to take advantage of the fact that the data is already in order to avoid a possible O(lg n) insertions/tree-balancing?

Sam Gomez
  • 75
  • 4
  • Ah, yes it is. Thanks! That'll teach me to search better first. – Sam Gomez Mar 21 '13 at 20:29
  • [Here](http://stackoverflow.com/questions/5279840/how-to-initialize-a-treemap-with-pre-sorted-data) is another solution. I have decided to simply use putAll() when copying from another TreeMap and a custom sorted structure when that is not available. – Sam Gomez Mar 21 '13 at 22:58

0 Answers0