Java Collectors.toSet() 和 HashSet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30082555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:05:29  来源:igfitidea点击:

Collectors.toSet() and HashSet

javajava-8java-streamcollectors

提问by Robert Bain

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:

我想要一个HashSet. 将调试器带到代码中,我确实得到了一个HashSet. 我查看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 guaranteesa 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.

合约保证a Set,执行决定 a HashSet;似乎合理。但是,我的实现需要由 a 保证的恒定时间查找HashSet,而不仅仅是任何旧的Set. 如果 的实现toSet()决定使用 say a FooSet,这完全在其权利范围内,我的实现就会受到损害。

What is the best practise solution to this problem?

这个问题的最佳实践解决方案是什么?

采纳答案by Tagir Valeev

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

如果你想要一个有保证的HashSet,使用Collectors.toCollection(HashSet::new).