java集合转换慢
IMap<Long, Vehicle> mapVehicles = // get all vehicles , total 2500 unit
Collection<Vehicle> collectionVeh = mapVehicles.values(); // fast
// I want to sort it so wrap to ArrayList
List<Vehicle> listVehicle = new ArrayList(collectionVeh .values()); // very slow
Collections.sort(listVehicle );// fast
如何快速将集合转换为列表?
谢谢。
IMap<Long, Vehicle> mapVehicles = // get all vehicles , total 2500 unit
Collection<Vehicle> collectionVeh = mapVehicles.values(); // fast
// I want to sort it so wrap to ArrayList
List<Vehicle> listVehicle = new ArrayList(collectionVeh .values()); // very slow
Collections.sort(listVehicle );// fast
How can i convert Collection to List very fastly ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的
Collection
不是List
,并且您希望将其作为List
,那么没有比执行某些操作更快的方法了就像new ArrayList(yourCollection)
。 (可以这么说,我不认为构造函数会执行任何您可以跳过的不必要的工作。)但是您可以做的是更改原始集合。如果它当前是一个
HashMap
,那么您的迭代所花费的时间将与其容量成正比。通过更改为LinkedHashMap
,您可以按与其大小成比例的时间对其进行迭代。 (可能差异可以忽略不计,但值得一试。)If you have a
Collection
that's not aList
, and you want to have it as aList
, there is no faster way than to do something likenew ArrayList(yourCollection)
. (I don't believe that constructor does any unnecessary work that you could skip, so to speak.)What you could do however is to change the original collection. If it's currently a
HashMap
your iteration will take time proportional to it's capacity. By changing to aLinkedHashMap
you can iterate over it in time proportional to it's size. (Probably a negligible difference, but it could be worth a try.)如果将车辆放入 TreeSet 中会更快吗?
Is it faster if you drop the vehicles in a TreeSet instead?
您可以尝试
Arrays.asList(collectionVeh.values().toArray)
吗?也许它会跑得更快?Could you please try
Arrays.asList(collectionVeh.values().toArray)
? May be it will run faster?