How to initialize a TreeMap with pre-sorted data?

点点圈 提交于 2019-11-27 06:15:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5279840/how-to-initialize-a-treemap-with-pre-sorted-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!