Running on Java 17-ea+15-1230 (Preview)
Home of The JavaSpecialists' Newsletter


Author: Dr Heinz M. KabutzDate: 2021-04-03Java Version: 11+Category: Tips and Tricks

Abstract: If we have a List<Stream<T>>, each stream with sorted elements, how can we generate a sorted Stream<T>, taking one at a time from each stream? In this newsletter we show how to do that with the Stream API and by writing our own MergingSortedSpliterator.


Welcome to the 289th edition of The Java(tm) Specialists' Newsletter. I know, I know, 36 hours ago I sent you a newsletter after two months of radio silence, and here is another one? Well, when I see an interesting puzzle, I find myself unable to resist trying to solve it. And that's what happened this morning. So here we are - I hope you enjoy it :-)

We have three upcoming LIVE virtual classes in April and May 2021:

  1. Refactoring to Streams and Lambdas for US$ 497 on April 6-7 2021 @ 9am-1pm Frankfurt Time.
  2. Extreme Java - Advanced Topics Java 17 Edition for EUR 1299 on April 19-20 2021 @ 9am-5pm Frankfurt Time. (almost sold out)
  3. Design Patterns Deep Dive for US$ 497 on May 11-12 2021 @ 7-11am Los Angeles Time.

My favourite course at the moment is the Refactoring to Streams and Lambdas course. We spend 8 hours ripping apart a 330k LOC application and replacing bits with more modern code. Too much fun! We still have a few places available for next week. The Advanced Topics Course is also very interesting. It is almost sold out though, so please grab the seats if you would like to join.


As I rubbed the sleep out of my eyes this morning, I vaguely made out the shape of a tweet with my name on it. Antoine DESSAIGNE (@adessaigne) had tweeted "Hello @java folks 👋, If you have a List<Stream<T>>, each stream with sorted elements, how can you generate a sorted Stream<T>, taking one at a time from each stream? Managed to do that using iterators but is there a clever way to do it with Stream API? Thanks 👍"

None of the Java greats had proposed an easy or performant solution, so I grabbed my laptop and started typing. Antoine had apparently created his own solution using Iterators, and I had in mind a solution using Spliterators. A Spliterator can easily be converted to a Stream using Having not seen Antoine's solution, I imagine that he did something along the same lines. Obviously we could just do:

In that case we would need to sort twice. I wanted to avoid that. However, the second sort would not be as expensive as the first. Timsort is efficient at sorting partially sorted lists. In addition, if we also parallelize the second stream sorting, then internally it will do a divide and conquer. There is a good chance that we would end up with chunks of items that are already mostly sorted.

But more fun is to write our own MergingSortedSpliterator. Some constraints are: the streams that are passed in have to have the sorted characteristic, which also implies that their Spliterator should return the Comparator used for sorting. All the streams must have used the same Comparator. The Comparator does not have to be the same instance, but they must match equals(). Another constraint is that this Spliterator does not support parallel streams. The characteristics are an AND of all the contained spliterators and the estimatedSize is a sum of the spliterators, using Long.MAX_VALUE if we overflow.

Note: We updated the class a bit by not reading the first element in the constructor. We also changed the spliterator to be distinct if all the contained streams are distinct. (suggestions by @tagir_valeev)

import java.util.*;
import java.util.function.*;

public class MergingSortedSpliterator<T> implements Spliterator<T> {
  private final List<Spliterator<T>> spliterators;
  private final List<Iterator<T>> iterators;
  private final int characteristics;
  private final Object[] nextItem;
  private final static Object START_OF_STREAM = new Object();
  private final static Object END_OF_STREAM = new Object();
  private final Comparator<? super T> comparator;
  private final boolean distinct;

  public MergingSortedSpliterator(Collection<Stream<T>> streams) {
    this.spliterators =
    if (!
        spliterator -> spliterator.hasCharacteristics(SORTED)))
      throw new IllegalArgumentException("Streams must be sorted");
    Comparator<? super T> comparator =
        .reduce(null, (a, b) -> {
          if (Objects.equals(a, b)) return a;
          else throw new IllegalArgumentException(
              "Mismatching comparators " + a + " and " + b);
    this.comparator = Objects.requireNonNullElse(comparator,
        (Comparator<? super T>) Comparator.naturalOrder());
    this.characteristics =
        .reduce((ch1, ch2) -> ch1 & ch2)
    this.distinct = hasCharacteristics(DISTINCT);

    // setting up iterators
    this.iterators =
    nextItem = new Object[streams.size()];
    Arrays.fill(nextItem, START_OF_STREAM);

  private Object fetchNext(Iterator<T> iterator) {
    return iterator.hasNext() ? : END_OF_STREAM;

  public boolean tryAdvance(Consumer<? super T> action) {
    Objects.requireNonNull(action, "action==null");
    if (nextItem.length == 0) return false;
    T smallest = null;
    int smallestIndex = -1;
    for (int i = 0; i < nextItem.length; i++) {
      Object o = nextItem[i];
      if (o == START_OF_STREAM)
        nextItem[i] = o = fetchNext(iterators.get(i));
      if (o != END_OF_STREAM) {
        T t = (T) o;
        if (smallest == null ||
  , smallest) < 0) {
          smallest = t;
          smallestIndex = i;

    // smallest might be null if the stream contains nulls
    if (smallestIndex == -1) return false;

    if (distinct) {
      for (int i = 0; i < nextItem.length; i++) {
        Iterator<T> iterator = iterators.get(i);
        while (nextItem[i] != END_OF_STREAM &&
  , (T) nextItem[i]) == 0) {
          nextItem[i] = fetchNext(iterator);
    } else {
      nextItem[smallestIndex] =

    return true;

  public Spliterator<T> trySplit() {
    // never split - parallel not supported
    return null;

  public long estimateSize() {
        .reduce((ch1, ch2) -> {
          long result;
          if ((result = ch1 + ch2) < 0) result = Long.MAX_VALUE;
          return result;

  public int characteristics() {
    return characteristics;

  public Comparator<? super T> getComparator() {
    return comparator;

We can then create a Stream from the Spliterator using MergingSortedSpliterator<>(streams), false). The false means that the stream will be sequential and not parallel. As mentioned above, parallel is not supported.

Here is a demo of the MergingSortedSpliterator at work:

import java.util.*;
import java.util.concurrent.*;

public class SortedStreamOfSortedStreams {
  private static final int SIZE = 5;

  public static void main(String... args) {
    List<Stream<Integer>> streams = List.of(

    Stream<Integer> numbers =
        new MergingSortedSpliterator<>(streams), false

  private static Stream<Integer> generateSortedRandom(int size) {
    return ThreadLocalRandom.current().ints(size, 0, size * 4)

For example, we might see output like this:


I ran some performance tests and as I expected, my MergingSortedSpliterator is faster than a sorted flatMap. However, even faster, at least on my machine, is a parallel sorted flatMap. Here is a basic performance test:

import java.util.*;
import java.util.function.*;

public class PerformanceTest {
  private static final int SIZE = 10_000_000;
  private static final
  List<Function<List<Stream<Integer>>, Stream<Integer>>> MERGERS =
          s ->
          s ->
          s ->
              new MergingSortedSpliterator<>(s), false

  public static void main(String... args) {
    for (int i = 0; i < 10; i++) {

  private static void test() {
    MERGERS.forEach(merger -> {
      List<Stream<Integer>> streams = makeStreams();
      long time = System.nanoTime();
      try {
        Stream<Integer> numbers = merger.apply(streams);
        numbers.forEach(i -> { });
      } finally {
        time = System.nanoTime() - time;
        System.out.printf("time = %dms%n", (time / 1_000_000));

  private static List<Stream<Integer>> makeStreams() {
    return Stream.generate(() -> generateSorted(SIZE))

  private static Stream<Integer> generateSorted(int size) {
    return IntStream.range(0, size).boxed();

On my 1-8-2 MacBook Pro the best results were:

Sorted flatMap sequential: 7.8 seconds
Sorted flatMap parallel:   2.1 seconds
MergingSortedSpliterator:  5.2 seconds

Thus the MergingSortedSpliterator would be faster than the sequential version and require less CPU cycles than the parallel version. Unless I was working with very large datasets, I would probably favour the sorted flatMap sequential version. Only catch is that we should make sure that the comparator is the same as for the original streams. My MergingSortedSpliterator takes care of that for us.

Thanks Antoine for the challenge. I enjoy solving puzzles like this, especially if they have some practical application and are not just interview questions or homework assignments :-)

Kind regards




We are always happy to receive comments from our readers. Feel free to send me a comment via email or discuss the newsletter in our JavaSpecialists Slack Channel (Get an invite here)

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Related Articles

Browse the Newsletter Archive

About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack 21

Superpack 21 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.