如何使用预先排序的数据初始化TreeMap? [英] How to initialize a TreeMap with pre-sorted data?

查看:553
本文介绍了如何使用预先排序的数据初始化TreeMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用使用 TreeMap 保持数据排序并具有log(n)查找和&插入。这在应用程序运行时的一般情况下效果很好,但是当应用程序首次启动时,我需要使用排序顺序(升序)中的数百万条长度来初始化TreeMap。

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).

由于这些初始化值已经排序,是否有任何方法可以将它们插入TreeMap而无需支付树插入的log(n)成本平衡?

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?

推荐答案

当然可以! TreeMap.putAll 方法(以及采用SortedMap的TreeMap构造函数)调用名为 buildFromSorted 内部,在文档中描述为:来自排序数据的线性时间树构建算法,这样听起来就像你想做的那样。

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.

只需给出 putAll 实现Map的方法,但是map的entryset迭代器( Map.entrySet()。iterator())返回你的排序值列表。

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.

这篇关于如何使用预先排序的数据初始化TreeMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆