How to initialize TreeMap with pre-sorted data?

My application uses TreeMap to sort data and search for (n) search queries and inserts. This works well in the general case when the application starts, but when the application starts, I need to initialize the TreeMap with several million lengths, which I get in sorted order (ascending).

Since these initialization values ​​are already sorted, is there a way to insert them into TreeMap without paying log (n) the cost of inserting and rebalancing the tree?

+5
source share
1 answer

Of course! The method TreeMap.putAll(and the TreeMap constructor that accepts SortedMap) calls inside itself a method called buildFromSortedthat is described in the documents as: "An algorithm for constructing a linear time algorithm from sorted data", so that it sounds as if it does what you want.

Just give the method putAllsomething that implements Map, but where the map line input iterator ( Map.entrySet().iterator()) returns a list of sorted values.

+10
source

All Articles