如何基于谓词创建实时子集合?

问题描述 投票:0回答:1

背景

我有一个界面

public interface ThingRegistry {

    public Set<Thing> getAllThings();
    public Set<Thing> getAllThingsWithProperty(String property);
}

以及实施

public class MemoryThingRegistry {
    private final Set<Thing> things = new HashSet<>();

    public Set<Thing> getAllThings() {
        return Collections.unmodifiableSet(this.things);
    }

    public Set<Thing> getAllThingsWithProperty(final String property) {
        return this.things.stream().filter((thing) -> thing.hasProperty(property)).collect(Collectors.toSet());
    }
}

问题

  • getAllThings()
    返回的集合将反映我的注册表中所做的任何更改
  • 但是,
    getAllThingsWithProperty()
    返回的Set不会反映这些变化

问题

有没有办法使用标准java库,或者一些非常常见的第三方库,使

getAllThingsWithProperty()
的返回值成为“实时”子
Set
? IE。它“由”原始
Set
“支持”,但每次访问时都会重新应用
Predicate
?最好是可以适用于任何
Collection
的东西,因为我有另一个使用
List
的注册表界面。

我知道我可以编写自己的

Set
实现,但我宁愿避免这种情况。

java collections functional-programming
1个回答
0
投票

而不是返回

Set<Thing>
的方法。您可以编写一个返回
Supplier<Set<Thing>>
的方法。每次你想要获取当前的
Set
时,你就调用
Supplier
get()
方法。

public Supplier<Set<Thing>> getAllThingsWithProperty(final String property) {
    return () -> this.things.stream().filter((thing) -> thing.hasProperty(property)).collect(Collectors.toSet());
}
© www.soinside.com 2019 - 2024. All rights reserved.