Collectors.toSet()和HashSet [英] Collectors.toSet() and HashSet

查看:1641
本文介绍了Collectors.toSet()和HashSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下示例代码行:

Set<String> someSet = someColletion.stream().map(p -> p.toString()).collect(Collectors.toSet());

我想要 HashSet 。将调试器带到代码中,我确实得到了一个 HashSet 。我看了 java.util.stream.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);
}

合约保证 a 设置,实现决定 HashSet ;看似合理。但是,我的实现需要由 HashSet 保证的常量时间查找,而不仅仅是任何旧的 Set 。如果 toSet()的实现决定使用一个完全在其权限范围内的 FooSet ,我的实现是已经妥协了。

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)

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

这篇关于Collectors.toSet()和HashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆