Custom spliterator for Collections.nCopies(n, obj).stream()

Paul Sandoz paul.sandoz at
Thu Jul 30 07:42:28 UTC 2015

On 30 Jul 2015, at 08:08, Tagir F. Valeev <amaembo at> wrote:

> Hello!
> PS> I don’t particular want to add a special spliterator for this
> PS> case to avoid some profile pollution. Will it not just push the
> PS> pollution further down the road to Spliterator.forEachRemaining? or to within other code?
> I just thought that the current idea is to create specialized
> spliterators for most methods returning streams.

Not without some evaluation of the benefits compared to the increased cost of code.

> If not, why
> String.chars()/AbstractStringBuilder.chars() in JDK9 use new
> IntCharArraySpliterator instead of already existing
> CharBuffer.wrap(this).chars() which produce similar performance in
> both sequential and parallel cases? Also for String an alternative
> would be
> return IntStream.range(0, value.length).map(i -> value[i]);

Since String is a commonly used class i opted for the most efficient solution (both for characters and code points, and shared across String and the builders).

> Which is actually similar to Collections.nCopies().stream().

Yes, but i doubt it is as commonly used as String and thus I don’t think the argument of profile pollution is sufficient reason to justify a specific implementation. In this case convenience won over more code.

> Also note that Collections class already contains singletonSpliterator
> which  creates  an  anonymous class. With my proposed change it can be
> replaced  with new ConstantSpliterator(1, element) without performance
> drop, so actual number of classes will not increase.

With reuse it becomes more compelling :-) In both cases of singleton/nCopies the spliterator characteristics can be the same and that of the already existing singleton spliterator implementation.

I would be happy to accept a patch (with tests, if existing tests do not cover this already, i suspect they might but we still need to check). Have you signed the OCA [1]. If so i can accept a patch from you and publish as a webrev for review.

> At very least why creating two distinct lambdas in
> and CopiesList.parallelStream()? They duplicate "i -> element", for
> which javac creates two separate methods (like lambda$stream$95(int)
> and lambda$parallelStream$96(int)) and in runtime two distinct
> anonymous classes may be created. It could be written instead
> public Stream<E> parallelStream() {
>    return stream().parallel();
> }

Yes, good point.



More information about the core-libs-dev mailing list