简体   繁体   English

Collectors.toSet() 和 HashSet

[英]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 .我想要一个HashSet Taking a debugger to the code, I am indeed getting a HashSet .将调试器带到代码中,我确实得到了一个HashSet I had a look at java.util.stream.Collectors.toSet() to observe the following code:我查看了java.util.stream.Collectors.toSet()以观察以下代码:

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 ;合约保证一个Set ,实现决定一个HashSet seems reasonable.似乎合理。 However, my implementation needs the constant time lookup guaranteed by a HashSet , not just any old Set .但是,我的实现需要由HashSet保证的恒定时间查找,而不仅仅是任何旧的Set If the implementation of toSet() decides to use say a FooSet , which is perfectly within its rights, my implementation is compromised.如果toSet()的实现决定使用一个FooSet ,这完全在它的权利范围内,我的实现就会受到影响。

What is the best practise solution to this problem?这个问题的最佳实践解决方案是什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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