Collectors.toSet() and HashSet

JavaJava 8Java StreamCollectors

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

If you want a guaranteed HashSet, use Collectors.toCollection(HashSet::new).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert BainView Question on Stackoverflow
Solution 1 - JavaTagir ValeevView Answer on Stackoverflow