Google Collections (Guava Libraries): ImmutableSet/List/Map and Filtering

廉价感情. 提交于 2019-12-19 17:46:59

问题


Assume that you want to build a copy of an ImmutableSet/List/Map object but filter out some of the original entries. One way to implement that is the following:

ImmutableList.copyOf(Iterables.filter(myObject, myObject.EQUALS));

where myObject.EQUALS is a predicate for the Iterables.filter() operation. I think this is a pretty elegant and easy-to-read implementation. However, one builds two list objects (first through the Iterables.filter(...) call, second through ImmutableList.copyOf(...)) which is very inefficient.

Does anybody know of a more efficient way to do it?

I guess the best thing would be to add filter predicates to the ImmutableSet/List/Map builders so that the object must be constructed only once. But unfortunately there is no such parameter.


回答1:


The result of Iterables.filter() is just a view over the data in myObject: the new list is only built by ImmutableList.copyOf() using the filtering iterator provided by the Iterable




回答2:


Look at Guava's Iterators

Specifically filter(Iterator unfiltered, Predicate predicate)



来源:https://stackoverflow.com/questions/6176918/google-collections-guava-libraries-immutableset-list-map-and-filtering

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