Collectors.toSet() and HashSet

天大地大妈咪最大 提交于 2019-12-03 03:23:45

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/30082555/collectors-toset-and-hashset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!