Take the following line of sample code:
Set<String> someSet = someColletion.stream().map(p -> p.toString()).collect(Collectors.toSet());
I want a HashSet. Taking a debugger to the code, I am indeed getting a HashSet. I had a look at java.util.stream.Collectors.toSet() to observe the following code:
public static <T> Collector<T, ?, Set<T>> toSet() {
return new CollectorImpl<>((Supplier<Set<T>>) HashSet::new, Set::add,
(left, right) -> { left.addAll(right); return left; },
CH_UNORDERED_ID);
}
The contract guarantees a Set, and implementation decides on a HashSet; seems reasonable. However, my implementation needs the constant time lookup guaranteed by a HashSet, not just any old Set. If the implementation of toSet() decides to use say a FooSet, which is perfectly within its rights, my implementation is compromised.
What is the best practise solution to this problem?
Tagir Valeev
If you want a guaranteed HashSet, use Collectors.toCollection(HashSet::new).
来源:https://stackoverflow.com/questions/30082555/collectors-toset-and-hashset