That seems too tricky for me since ImmutableSet
instances are only built with ImmutableSet.Builder
instances, which don't implement Collection
so you can't just use Collectors.toCollection(ImmutableSet::new)
or Collectors.toCollection(ImmutableSet.Builder::new)
.
The toMap collector can be used to collect Stream elements into a Map instance. To do this, we need to provide two functions: keyMapper.
An immutable list is created this way. List<Person> immutableList = Collections. unmodifiableList(new ArrayList<>(persons)); This creates an immutable list since a conversion constructor is being used.
The toList() method of Collectors Class is a static (class) method. It returns a Collector Interface that gathers the input data onto a new list. This method never guarantees type, mutability, serializability, or thread-safety of the returned list but for more control toCollection(Supplier) method can be used.
This is built into guava now,
ImmutableSet#toImmutableSet
Use like,
something.stream().collect(ImmutableSet.toImmutableSet())
In fact, 3 months after :-), instead of defining a whole class for this, you can use Collector.of
and wrap it in a simple utility method:
public static <T> Collector<T, Builder<T>, ImmutableSet<T>> immutableSetCollector() {
return Collector.of(Builder<T>::new, Builder<T>::add, (s, r) -> s.addAll(r.build()), Builder<T>::build);
}
and then:
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
....
ImmutableSet<Point2D> set =
Stream.of(new Point2D(1, 2), ...).collect(immutableSetCollector());
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