What are the considerations of using Iterable
For example, consider implementing a type that is primarily concerned with contai
See "Why so much emphasis on Iterators and Iterables?" on the Google Collection FAQ for a decent argument for preferring Iterators, especially when dealing with a lot of data. One analogy that might help is to think the difference between forward-only read-only cursors and scrollable cursors.
Users of Spring Data JPA
will find that the Repositories
return collections of type Iterable<T>.
On projects I've worked on in the past that use Spring
, I've found that the need to operate on a Collection after retrieval has often dictated that Iterable<T>
is used in the business layer rather than Collection<T>
in order to select an Object T
from the collection.
All Collections are Iterable
(that is the interfaces which extend the Collection
interface, so not Map
!), so using Iterable
in the business layer is merely a case of referring to a Collection by its super type and still allows the use of for-each
to iterate.
If you need to manipulate the contents of a collection, a convenience method would allow you to populate a new Collection
, so you can make use of contains()
, remove()
, etc with the original collection data.
Alternatively, convenience methods are provided for this purpose by popular third party APIs such as Google Guava and Apache Commons.
Many of the collection types existed before Iterable<T> (which was only introduced in 1.5) - there was little reason to add a constructor to accept Iterable<T>
as well as Collection<T> but changing the existing constructor would have been a breaking change.
Personally I would use Iterable<T>
if that allows you to do everything you want it to. It's more flexible for callers, and in particular it lets you do relatively easy filtering/projection/etc using the Google Java Collections (and no doubt similar libraries).