Collectors.toSet() small performance improvement

Tagir F. Valeev amaembo at gmail.com
Tue Aug 9 07:19:44 UTC 2016


Hello, Aleksey!

Thank you for review.

AS> Good trick, but does it work properly with the sets that care about the
AS> add order, e.g. LinkedHashSet? I guess our saving grace here is
AS> Collector.toSet() is declared UNORDERED, so we can disturb the encounter
AS> order without violating the API contract.

This implementation is bound to HashSet which is created right here,
in supplier:

return new CollectorImpl<>((Supplier<Set<T>>) HashSet::new, Set::add,... )

No other set implementation is possible here. Users who want to use
custom set should use Collectors.toCollection(LinkedHashSet::new)
which I'm not going to change as indeed here order might be important.

AS> I would make it a bit cleaner though:

AS> (left, right) -> {
AS>     if (left.size() < right.size()) {
AS>        right.addAll(left); return right;
AS>     } else {
AS>        left.addAll(right); return left;
AS>     }
AS> }

Agreed.

With best regards,
Tagir Valeev.



More information about the core-libs-dev mailing list