The Javadoc for com.google.common.collect.ImmutableSet
suggests that there are two ways to create instances of ImmutableSet<E>
from elements of type E
(e.g. E e1
and E e2
) that are not already in a collection (i.e. ignoring the copyOf
method to create from existing collection):
The "of" method:
ImmutableSet<E> set = ImmutableSet.of(e1, e2);
Builder:
ImmutableSet<E> set = new ImmutableSet.Builder<E>().add(e1).add(e2).build();
Both methods use ImmutableSet.Builder#construct
in the end but which one should I prefer?
It completely depends upon how you're going to build ImmutableSet
. If you've all the elements available at one place, then directly use of(E...)
method. That would certainly be shorter.
But if somehow, you're getting elements from different places, that would mean, your object state is not finalized at one place, but after accumulating data on the flow. Then you will have to go with Builder
way. Create a Builder
, and keep on adding elements as and when you get. And then when you're done, just call build()
to get ImmutableSet
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With