private SortableChunk readAllAndMergeIn(Collection<Chunk> others) {
      // first, grow this chunk
      int newItems = itemCount;
      int newBytes = bytesInMemory;
      for (var other : others) {
        if (Integer.MAX_VALUE - newItems < other.itemCount) {
          throw new IllegalStateException("Too many items in merged chunk: " + itemCount + "+" +
            others.stream().map(c -> c.itemCount).toList());
        }
        if (Integer.MAX_VALUE - newBytes < other.bytesInMemory) {
          throw new IllegalStateException("Too big merged chunk: " + bytesInMemory + "+" +
            others.stream().map(c -> c.bytesInMemory).toList());
        }
        newItems += other.itemCount;
        newBytes += other.bytesInMemory;
      }
      // then read items from all chunks into memory
      SortableChunk result = new SortableChunk(newItems);
      result.readAll(this);
      itemCount = newItems;
      bytesInMemory = newBytes;
      for (var other : others) {
        result.readAll(other);
      }
      if (result.i != itemCount) {
        throw new IllegalStateException("Expected " + itemCount + " features in " + path + " got " + result.i);
      }
      return result;
    }
An output segment that can be sorted with a fixed amount of RAM.
planetiler-core/src/main/java/com/onthegomap/planetiler/collection/ExternalMergeSort.java