[英]List masking elements from another List in Java
How can I make a List
or similar Collection
that represents a subset of another collection, masking (filtering out) unwanted elements but without creating an entirely new collection structure? 我怎样才能做一个List
或类似的Collection
,代表另一个集合的子集,屏蔽(过滤掉)不想要的成分,但没有创建一个全新的集合结构?
The second list could then be more quickly modified by enabling/disabling the visibility of individual elements. 然后可以通过启用/禁用各个元素的可见性来更快地修改第二个列表。 Doing so should be more performant than constantly rebuilding a second separate collection structure. 与不断重建另一个单独的收集结构相比,这样做应具有更高的性能。
I imagine some kind of bit-map view into the original collection. 我想象原始集合中有某种位图视图。
Ideally this would be thread-safe, and would fail-fast if the original collection were modified. 理想情况下,这将是线程安全的,并且如果原始集合被修改,则会快速失败。
For example, two masked collections backed by the same master collection: 例如,由同一主集合支持的两个蒙版集合:
canine
containing [ dog , wolf ] with no references to the other elements. 被屏蔽的集合可能被命名为canine
其中包含[dog,wolf],但未引用其他元素。 feline
containing [ cat , lion ]. 另一个蒙版的集合可能是包含[cat,lion]的feline
。 Another example: We have a list of many LocalDate
objects. 另一个示例:我们有许多LocalDate
对象的列表。 The user selects some of those dates for some purpose, perhaps selecting only weekdays but not weekends. 用户出于某些目的选择其中一些日期,也许只选择工作日,而不选择周末。 Then the user changes their selection, making a manual exception for certain dates. 然后,用户更改其选择,对某些日期进行手动例外。 Rather than build a new list each time of selected elements, a masked collection would be tracking which ones are selected with the others being ignored by omission. 一个被遮罩的集合不是在每次选择元素时都建立一个新列表,而是要跟踪选择了哪些元素,而忽略其他元素。
I would use filter categories using mask bits. 我将使用掩码位使用过滤器类别。 Each different type of element would have different mask bits: 每种不同类型的元素将具有不同的掩码位:
enum CategoryBits {
CATEGORY_A = 0x0001;
CATEGORY_B = 0x0002;
CATEGORY_C = 0x0004;
}
Then for define your mask bits on which categories you want to include: 然后定义要包括哪些类别的掩码位:
enum MaskBits {
filter1 = CATEGORY_A; //gets only CATEGORY_A items
filter2 = CATEGORY_A | CATEGORY_B; //gets CATEGORY_A and CATEGORY_B items
}
So every item in your collection would have a function: 因此,您收藏中的每个商品都将具有以下功能:
CategoryBits categoryBits() const { return CATEGORY_A; } //return whatever category this item is
Depending on which items you want to filter you can then set the MASK_BITS for the container. 然后,根据要过滤的项目,可以为容器设置MASK_BITS。 So now for filtering you just have to do: 因此,现在只需进行过滤即可:
if(MASK_BITS & item.category() != 0) { //this item is in the categories you want }
Which is very fast. 这是非常快的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.