[英]HashBag in-place remove
There are a large number of elements saved in a HashBag
(of Eclipse Collections framework). 在
HashBag
(Eclipse Collections框架)中保存了大量元素。 Now all elements with less than k occurrences should be removed. 现在应删除所有出现次数少于k的元素。
This could be done with: 这可以通过以下方式完成:
bag.removeAll(bag.selectByOccurrences(n->n<k));
Downside is, this creates a temporary bag instance which in our case consumes much memory. 不足之处是,这会创建一个临时包实例,在我们的例子中会占用大量内存。
So I'm looking for an in-place removal approach, eg with an iterator. 所以我正在寻找一种就地删除方法,例如使用迭代器。 The iterator returned by
iterator()
iterates n times over an element with n occurrences which isn't suitable CPU wise. 迭代
iterator()
返回的iterator()
n次出现的元素上迭代n次,这不适合CPU。 Better would be iterating over all distinct keys of the underlying ObjectIntMap
. 更好的是迭代底层
ObjectIntMap
所有不同键。 In the source code you can find a method AbstractHashBag.getKeysView()
but it's protected. 在源代码中,您可以找到
AbstractHashBag.getKeysView()
方法,但它受到保护。 Is there a way to access it via public API or any other ideas to remove such elements in-place? 有没有办法通过公共API或任何其他想法访问它以便就地删除这些元素?
If you can replace the original bag, instead of mutating it, you can just use the selectByOccurrences
with the reverse predicate. 如果你可以替换原始包,而不是改变它,你可以使用
selectByOccurrences
和反向谓词。
If that won't work, the following solution still creates a temporary bag, but should be more efficient than removeAll(Collection)
. 如果这不起作用,以下解决方案仍然会创建一个临时包,但应该比
removeAll(Collection)
更有效。
MutableBag<Integer> bag = Interval.oneTo(10).toBag()
.withAll(Interval.oneTo(10))
.withAll(Interval.evensFromTo(1, 10));
// Removes all odd numbers since they only occur twice
bag.selectByOccurrences(n -> n < 3).forEachWithOccurrences(bag::removeOccurrences);
For this use case, it seems like it would be useful to add a new method on MutableBag
called removeIfOccurrences(IntPredicate)
. 对于这个用例,似乎在
MutableBag
上添加一个名为removeIfOccurrences(IntPredicate)
的新方法会很有用。 I think this would make sense to add as an API if you'd like to create an issue and/or make a contribution to the library. 我认为,如果您想创建问题和/或为库做出贡献,那么添加为API是有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.