本文介绍了从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?

然后,通过启用/禁用单个元素的可见性,可以更快地修改第二个列表。这样做应该比不断重建第二个单独的收集结构更有效。

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.

我想象某种 view into the original collection。

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.


  • 主集合可能是[狗,cockatiel,猫,狮子,狼,蜂鸟]。

  • 隐藏的集合可能命名为 canine ,其中包含[dog,wolf],但没有引用其他元素。

  • 另一个掩码集合可能是包含[cat,lion]的名称 feline

  • The master collection might be [ dog , cockatiel , cat , lion , wolf , hummingbird ].
  • A masked collection might be named canine containing [ dog , wolf ] with no references to the other elements.
  • Another masked collection might be name feline containing [ cat , lion ].

另一个例子:我们有许多 LocalDate 对象的列表。用户为某些目的选择某些日期,可能只选择工作日,但不选择周末。然后,用户更改其选择,对某些日期进行手动例外。

Another example: We have a list of many LocalDate objects. 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
}

函数:

CategoryBits categoryBits() const { return CATEGORY_A; } //return whatever category this item is

根据您要过滤的项目,容器的MASK_BITS。现在过滤你只需要做:

Depending on which items you want to filter you can then set the MASK_BITS for the container. So now for filtering you just have to do:

if(MASK_BITS & item.category() != 0) { //this item is in the categories you want }

这是非常快的。

这篇关于从Java中的另一个列表中列出屏蔽元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 14:08