Collections.emptyList().spliterator() is not ORDERED

Tagir F. Valeev amaembo at gmail.com
Sun Sep 6 10:21:11 UTC 2015


Hello!

As Paul Sandoz pointed out in the "Custom spliterator for
Collections.nCopies(n, obj).stream()" discussion, the
List.spliterator() is specified to be ORDERED. However
Collections.emptyList().spliterator() violates this specification:

System.out.println(Collections.emptyList()
  .spliterator().hasCharacteristics(Spliterator.ORDERED));
// prints false

This becomes critical if I want to concatenate streams from the two
lists returned from two different methods (one of which returned
emptyList) and process the result in parallel. For example:

List<Integer> list1 = IntStream.range(0, 100).boxed().collect(Collectors.toList());
List<Integer> list2 = Collections.emptyList();
System.out.println(Stream
      .concat(list1.stream(), list2.stream()).parallel()
      .filter(x -> x >= 0).limit(10).collect(Collectors.toList()));

This code unexpectedly prints some random subset. This can be fixed by
replacing list2 with

List<Integer> list2 = Arrays.asList();

As Arrays.asList().spliterator() is ordered, the resulting stream is
ordered as well, so we see [0, ..., 9] as expected.

Looks like a bug in emptyList() implementation.

With best regards,
Tagir Valeev.




More information about the core-libs-dev mailing list