Google Collections(Guava Libraries):ImmutableSet / List / Map and Filtering
假设您要构建ImmutableSet
/ List
/ Map
对象的副本,但过滤掉一些原始条目。 实现这一目标的一种方法如下:
ImmutableList.copyOf(Iterables.filter(myObject, myObject.EQUALS));
其中myObject.EQUALS
是Iterables.filter()
操作的谓词。 我认为这是一个非常优雅且易于阅读的实现。 但是,一个构建两个列表对象(首先通过Iterables.filter(...)
调用,第二个通过ImmutableList.copyOf(...)
)这是非常低效的。
有人知道更有效的方法吗?
我想最好的办法是将过滤谓词添加到ImmutableSet
/ List
/ Map
构建器中,这样对象必须只构造一次。 但不幸的是,没有这样的参数。
Iterables.filter()
的结果只是对myObject
数据的一个视图:新列表只由ImmutableList.copyOf()
使用Iterable
提供的过滤迭代器构建。
看看番石榴的迭代器
特别是filter(Iterator未过滤,谓词谓词)