public static <K, T> Seq<Tuple2<K, Seq<T>>> grouped(Seq<? extends T> seq, Function<? super T, ? extends K> classifier) {
        final Iterator<? extends T> it = seq.iterator();

        class ClassifyingIterator implements Iterator<Tuple2<K, Seq<T>>> {
            final Map<K, Queue<T>> buffers = new LinkedHashMap<>();
            final Queue<K> keys = new LinkedList<>();

            class Classification implements Iterator<T> {
                final K key;
                Queue<T> buffer;

                Classification(K key) {
                    this.key = key;
                }

                void fetchClassification() {
                    if (buffer == null)
                        buffer = buffers.get(key);

                    while (buffer.isEmpty() && it.hasNext())
                        fetchNextNewKey();
                }

                @Override
                public boolean hasNext() {
                    fetchClassification();
                    return !buffer.isEmpty();
                }

                @Override
                public T next() {
                    return buffer.poll();
                }
            }

            void fetchClassifying() {
                while (it.hasNext() && fetchNextNewKey());
            }

            boolean fetchNextNewKey() {
                T next = it.next();
                K nextK = classifier.apply(next);

                Queue<T> buffer = buffers.get(nextK);

                try {
                    if (buffer == null) {
                        buffer = new ArrayDeque<>();
                        buffers.put(nextK, buffer);
                        keys.add(nextK);
                        return false;
                    }
                }
                finally {
                    buffer.offer(next);
                }

                return true;
            }

            @Override
            public boolean hasNext() {
                fetchClassifying();
                return !keys.isEmpty();
            }

            @Override
            public Tuple2<K, Seq<T>> next() {
                K nextK = keys.poll();
                return tuple(nextK, seq(new Classification(nextK)));
            }
        }

        return seq(new ClassifyingIterator()).onClose(seq::close);
    }
Classify this stream's elements according to a given classifier function
<p>
<pre><code>
// Seq(tuple(1, Seq(1, 3, 5)), tuple(0, Seq(2, 4, 6)))
Seq.of(1, 2, 3, 4, 5, 6).grouped(i -> i % 2 )
// Seq(tuple(true, Seq(1, 3, 5)), tuple(false, Seq(2, 4, 6)))
Seq.of(1, 2, 3, 4, 5, 6).grouped(i -> i % 2 != 0)
</code></pre>

This is a non-terminal analog of {@link #groupBy(Stream, Function)})
@see #groupBy(Function)
@see #partition(Predicate)
jOOL/src/main/java/org/jooq/lambda/Seq.java