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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With