Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out list of elements in a "lazy" way

Tags:

java

I have a list of objects and I want to create another list, which will include only objects for which the method acceptable() returns "true". My problem is that I want to make this selection done only on demand. In other words, I want a new list to be calculated and populated only when its iterator() method is called. Are there any libraries for that in Java?

I'm using JDK7

like image 334
Bernie Noel Avatar asked Mar 17 '23 19:03

Bernie Noel


1 Answers

Google Guava has a lot of helper methods for that type of functionality. What you want is already implemented.

Iterators.filter if you want to fiter an Iterator from a collection.

Iterables.filter if you need an instance of Iterable, for example to use it in "for-each" type of loops.

There is also Collections2.filter if you need also other collection methods to be preprocessed with the filter.

like image 78
Ramon Rivas Avatar answered Mar 20 '23 09:03

Ramon Rivas