Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create collection from Iterable in java?

For example, I have set of geometrical figures:

Set<Figure> figures;

There are two types of Figure: Square and Circle.

I want to get set of squares using google collections:

Iterables.filter(figures,squarePredicate);

But filter method return Iterable... How can I create Set from Iterable? (without using loop on Iterable)

like image 918
Artyom Chernetsov Avatar asked Oct 21 '11 14:10

Artyom Chernetsov


1 Answers

I think you need to rethink your requirements. You need a set of squares. Why?

A set gives you uniqueness and iteration, nothing more. You have uniqueness in your Iterable, because the source is a set, and you can iterate over the items in an Iterable. So why would you need the set?

There are only two possible reasons: either you are working with an API that needs a Set (or Collection) parameter, or you need to somehow display the Set's size.

In these cases, use Sets.newHashSet(iterable) to create a Set (on one hand of course that requires a full iteration, on the other hand: you will need a full iteration at one point anyway when you are iterating over the values, so why not do it now?). Otherwise, just use the Iterable and forget about a Set.

like image 150
Sean Patrick Floyd Avatar answered Oct 16 '22 22:10

Sean Patrick Floyd