简体   繁体   English

如何在不使用迭代器进行迭代的同时从集合中删除元素

[英]How to remove elements from collection while iterating without iterator

Let's say I've got a list of Strings (simplification) 假设我有一个字符串列表(简化)

fullList = {a,b,c,d,a,d,c,b}

and I want to find couples like 我想找到像

couplesList = {{a,a},{b,b}, ...}

The way I'm approaching this problem at the moment is 我现在解决这个问题的方法是

  1. Get first element 获取第一个元素
  2. Use guava predicate to find proper object 使用番石榴谓词找到合适的对象
  3. What now? 现在怎么办?

I'm ending up having 2 objects {a,a} but I can't remove them from fullList because I'm not using an "iterator" style of iterating (because I'm using Guava predicate it wouldn't work anyway - since I don't have iterator pointer to element that was find by Itarables.find(...) function). 我最终有2个对象{a,a},但是我无法从fullList删除它们,因为我没有使用“迭代器”样式进行迭代(因为我使用的是Guava谓词,所以无论如何都无法工作-因为我没有Itarables.find(...)函数找到的指向元素的迭代器指针)。

I want to do it in "efficient" way as well, so I want to avoid multiple nested loops etc. 我也想以“高效”的方式做到这一点,所以我想避免多个嵌套循环等。

Any ideas how to approach this problem more correctly/efficient way ? 任何想法如何更正确/有效地解决这个问题? I'm bit stuck. 我有点卡住了。

I would create a frequency count for each of the elements. 我将为每个元素创建一个频率计数。 In Guava terms this is a MultiSet. 用番石榴术语来说,这是一个多集。 From that you can create a collection of pairs, and another collection of the singles. 由此,您可以创建一个对的集合,以及一个单身的另一个集合。 This can be done with one pass of the original list and one pass of the frequency count map. 可以通过一遍原始列表和一遍频率计数图来完成。 ie O(n) 即O(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 迭代时从集合中删除元素 - Remove elements from collection while iterating 如何在迭代Collection时安全地从Collection中删除其他元素 - How to safely remove other elements from a Collection while iterating through the Collection Java:如何在迭代/添加元素时从列表中删除元素 - Java: How to remove elements from a list while iterating over/adding to it 迭代时从ArrayList中删除奇数元素 - Remove odd elements from ArrayList while iterating "如何在迭代时删除和添加元素到 TreeMap?" - How to remove and add elements to TreeMap while iterating? 在迭代Collection时删除元素 - removing elements while iterating the Collection 迭代事件处理程序集合时,如何安全地从*回调中删除处理程序? - While iterating over a collection of event handlers, how do you safely remove a handler from *within* a callback? 如果HashSet,ArrayList返回的迭代器是快速失败的,我们如何使用迭代器remove()从Collection中删除元素 - If Iterators returned by HashSet, ArrayList are fail-fast, how can we use iterator remove() to remove elements from Collection Java Guava:在迭代时从Multimap中删除并放回元素 - Java Guava: Remove and put back elements from Multimap while iterating 从列表中删除前“n”个元素而不进行迭代 - Remove first 'n' elements from list without iterating
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM