开发者社区> 问答> 正文

removeAll()方法花费很长时间

List<Batch> vAllBatchList = getAllBatchCollection().toList(); //Has 700k records
List<Batch> vKeepableBatchCollection = getKeepableBatchCollection(pDaysKeepHistory).toList(); //has 600k records
vAllBatchList.removeAll(vKeepableBatchCollection);

在上面的第三行中,removeAll方法花费太多时间来完成。如何在这里优化removeAll方法?

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 19:37:10 914 0
1 条回答
写回答
取消 提交回答
  • 如果将List要删除的element的转换为Set,则应该更快:

    vAllBatchList.removeAll(new HashSet<>(vKeepableBatchCollection));
    

    这是假设Batch类覆盖hashCode和equals正确。

    说明:removeAllfor ArrayList(我假设您vAllBatchList List是ArrayList)对List在其上被调用的所有元素进行迭代,并检查所传递的Collection内容是否包含这些元素。如果通过Collection是Set,contains将有望固定时间(O(1)),而如果Collection是List,它需要线性时间(O(n))。

    当然,如果您可以直接生成Setof的元素,vKeepableBatchCollection而不是先创建a List然后将其转换为a Set,那就更好了。

    回答来源:Stack Overflow

    2020-03-22 19:38:19
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载