Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you make a java.util.stream.Collector that collects to com.google.common.collect.ImmutableSet?

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).

like image 228
gvlasov Avatar asked Dec 22 '14 23:12

gvlasov


People also ask

Which method of collector class can be used to store the result of a Stream in map?

The toMap collector can be used to collect Stream elements into a Map instance. To do this, we need to provide two functions: keyMapper.

How do you make a list object immutable using streams API?

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.

What implementation of list does the collectors toList () create?

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.


2 Answers

This is built into guava now,

ImmutableSet#toImmutableSet

Use like,

something.stream().collect(ImmutableSet.toImmutableSet())
like image 180
sbridges Avatar answered Nov 09 '22 13:11

sbridges


In fact, 3 months after :-), instead of defining a whole class for this, you can use Collector.ofand 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());
like image 23
Alexis C. Avatar answered Nov 09 '22 13:11

Alexis C.