List masking elements from another List in Java

£可爱£侵袭症+ 提交于 2019-12-25 09:15:58

问题


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.

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:

  • 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 ].

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.


回答1:


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. 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.



来源:https://stackoverflow.com/questions/39176755/list-masking-elements-from-another-list-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!