3 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
為了使其更具可讀性,在這種情況下有Collection::addAll并Collection::removeAll使用,您的代碼可以是:
// create a new Collection where you use filter to search only the Object you want
Collection<Object> filterdCollection = myFirstCollection.stream()
.filter(o -> conditionReturningTrue(o))
.collect(Collectors.toCollection(LinkedHashSet::new));
// use allAll to add all the filtered Object to the second collection
mySecondCollection.addAll(filterdCollection);
// use removeAll to remove all the filtered Object from the first collection
myFirstCollection.removeAll(filterdCollection);

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
首先,你應(yīng)該爭(zhēng)取正確。對(duì)于大多數(shù)集合,禁止在迭代時(shí)修改源集合。您可能會(huì)ConcurrentModificationException嘗試一段時(shí)間,但即使它碰巧無一例外地運(yùn)行,代碼仍然不正確。只是這個(gè)錯(cuò)誤并不總是被檢測(cè)到(這是一個(gè)盡力而為的檢查,試圖避免浪費(fèi)太多的性能)。這適用于forEach(…)、 以及stream().forEach(…)和 for-each 循環(huán) ( for(variable declaration: collection))
在迭代時(shí)刪除元素的唯一支持是通過手動(dòng)Iterator使用:
for(Iterator<Object> it = myFirstCollection.iterator(); it.hasNext(); ) {
Object o = it.next();
if(conditionReturningTrue(o)) {
it.remove();
mySecondCollection.add(o);
}
}
替代方法是批量方法。
首先,就像這個(gè)和那個(gè)答案中所示,創(chuàng)建要首先傳輸?shù)乃性氐母北尽?/p>
其次,您可以使用
myFirstCollection.removeIf(o -> conditionReturningTrue(o) && mySecondCollection.add(o));
的default實(shí)現(xiàn)removeIf使用了Iterator一個(gè)類似于上面的循環(huán)。但是,像這樣的集合ArrayList提供了它們自己的 實(shí)現(xiàn)removeIf,以克服Iterator循環(huán)的二次時(shí)間復(fù)雜度。

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以通過避免removeAll(對(duì)于某些Collection對(duì)象查找需要線性搜索的Lists ,例如s,這可能需要二次時(shí)間)來提高性能,方法是使用Collectors.partitioningBy將原始文件拆分Collection為兩個(gè)Lists:
Collection<Object> myFirstCollection; //let's consider it instanciated and populated
Collection<Object> mySecondCollection; //same for this one
Map<Boolean,List<Object>> partition =
myFirstCollection.stream()
.collect(Collectors.partitioningBy(o -> conditionReturningTrue(o)));
myFirstCollection.clear();
myFirstCollections.addAll(partition.get(false));
mySecondCollection.addAll(partition.get(true));
另一方面,如果只有少數(shù)元素應(yīng)該從 移動(dòng)myFirstCollection到,則此解決方案可能效率較低mySecondCollection。
添加回答
舉報(bào)