Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a TreeMap with pre-sorted data?

My app uses a TreeMap to keep data sorted and have log(n) lookups & inserts. This works great in the general case while the app is running, but when the app first starts, I need to initialize the TreeMap with several million longs that I get in sorted order (ascending).

Since these initialization values are already sorted, is there any way to insert them into the TreeMap without paying the log(n) cost of tree insertion and re-balancing?

like image 487
Yevgeniy Brikman Avatar asked Mar 12 '11 00:03

Yevgeniy Brikman


1 Answers

Sure! The TreeMap.putAll method (and the TreeMap constructor that takes a SortedMap) calls a method called buildFromSorted internally, which is described in the docs as: "Linear time tree building algorithm from sorted data", so that sounds like it does what you want.

Just give the putAll method something that implements Map, but where the map's entryset iterator (Map.entrySet().iterator()) returns your list of sorted values.

like image 177
Neil Avatar answered Sep 30 '22 17:09

Neil