简体   繁体   中英

Collectors.toSet() and HashSet

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?

如果您想要有保证的HashSet ,请使用Collectors.toCollection(HashSet::new)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM