背景
我有一个界面
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
实现,但我宁愿避免这种情况。
而不是返回
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());
}