java arraylist 过滤,Java:高效的ArrayList筛选?

博客讨论了在Java中高效地从ArrayList中过滤并移除元素的方法。指出简单的迭代删除方式由于ArrayList内部实现会导致大量元素复制,效率低下。推荐使用创建新列表保留所需元素或Java 8以后的lambda表达式和流来提高效率。
摘要由CSDN通过智能技术生成

I need to filter an ArrayList and remove found elements. Being relatively new to Java, I'm wondering what the most efficent method is to achieve this (matters because it runs on mobile devices). Currently I do this:

// We display only top-level dealers (parentId=-10)

ArrayList subDealers = new ArrayList();

for (DealerProductCount dealer : wsResponse.Dealers) {

if (dealer.ParentId != -10) subDealers.add(dealer);

}

wsResponse.Dealers.removeAll(subDealers);

Can it be done without temporary objects? Maybe by directly manipulating (removing) elements of the list being iterated?

解决方案

Efficiently removing a number of elements from an ArrayList requires some thought. The naive approach is something like this:

Iterator it = wsResponse.Dealers.iterator();

while (it.hasNext()) {

if (it.next().ParentId != -10) {

it.remove();

}

}

The problem is that each time you remove an element you copy (on average) half of the remaining elements. This is because removing an element from an ArrayList entails copying all elements after element removed one position to the left.

Your original solution involving the list of elements to be removed essentially does the same thing. Unfortunately, the properties of an ArrayList don't allow removeAll to do better than the above.

If you expect to remove a number of elements, the following is more efficient:

ArrayList retain =

new ArrayList(wsResponse.Dealers.size());

for (DealerProductCount dealer : wsResponse.Dealers) {

if (dealer.ParentId == -10) {

retain.add(dealer);

}

}

// either assign 'retain' to 'wsResponse.Dealers' or ...

wsResponse.Dealers.clear();

wsResponse.Dealers.addAll(retain);

We are copying (almost) the entire list twice, so this should break even (on average) if you remove as few as 4 elements.

It is interesting to note that functional programming languages / libraries typical support a filter method, and that can do this task in one pass through the list; i.e. a lot more efficiently. I think we can expect significant improvements if / when Java supports lambdas, and the collection APIs are enhanced to use them.

UPDATE and with Java 8 lambdas and streams, we get them ... for this use-case.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值