All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.landawn.abacus.util.stream.IteratorStream Maven / Gradle / Ivy

There is a newer version: 1.2.9
Show newest version
/*
 * Copyright (C) 2016 HaiYang Li
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.landawn.abacus.util.stream;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;

import com.landawn.abacus.util.ByteIterator;
import com.landawn.abacus.util.CharIterator;
import com.landawn.abacus.util.DoubleIterator;
import com.landawn.abacus.util.FloatIterator;
import com.landawn.abacus.util.Indexed;
import com.landawn.abacus.util.IntIterator;
import com.landawn.abacus.util.LongIterator;
import com.landawn.abacus.util.LongMultiset;
import com.landawn.abacus.util.Multimap;
import com.landawn.abacus.util.Multiset;
import com.landawn.abacus.util.N;
import com.landawn.abacus.util.Nullable;
import com.landawn.abacus.util.ShortIterator;
import com.landawn.abacus.util.Try;
import com.landawn.abacus.util.function.BiConsumer;
import com.landawn.abacus.util.function.BiFunction;
import com.landawn.abacus.util.function.BiPredicate;
import com.landawn.abacus.util.function.BinaryOperator;
import com.landawn.abacus.util.function.Consumer;
import com.landawn.abacus.util.function.Function;
import com.landawn.abacus.util.function.Predicate;
import com.landawn.abacus.util.function.Supplier;
import com.landawn.abacus.util.function.ToByteFunction;
import com.landawn.abacus.util.function.ToCharFunction;
import com.landawn.abacus.util.function.ToDoubleFunction;
import com.landawn.abacus.util.function.ToFloatFunction;
import com.landawn.abacus.util.function.ToIntFunction;
import com.landawn.abacus.util.function.ToLongFunction;
import com.landawn.abacus.util.function.ToShortFunction;
import com.landawn.abacus.util.function.TriFunction;
import com.landawn.abacus.util.stream.ObjIteratorEx.QueuedIterator;

/**
 * This class is a sequential, stateful and immutable stream implementation.
 *
 * @param 
 * @since 0.8
 * 
 * @author Haiyang Li
 */
class IteratorStream extends AbstractStream {
    final ObjIteratorEx elements;

    Nullable head;
    Stream tail;

    Stream head2;
    Nullable tail2;

    IteratorStream(final Iterator values) {
        this(values, null);
    }

    IteratorStream(final Iterator values, final Collection closeHandlers) {
        this(values, false, null, closeHandlers);
    }

    IteratorStream(final Iterator values, final boolean sorted, final Comparator comparator, final Collection closeHandlers) {
        super(sorted, comparator, closeHandlers);

        N.requireNonNull(values);

        ObjIteratorEx tmp = null;

        if (values instanceof ObjIteratorEx) {
            tmp = (ObjIteratorEx) values;
        } else {
            tmp = new ObjIteratorEx() {
                @Override
                public boolean hasNext() {
                    return values.hasNext();
                }

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

        this.elements = tmp;
    }

    IteratorStream(final Stream stream, final boolean sorted, final Comparator comparator, final Set closeHandlers) {
        this(stream.iterator(), sorted, comparator, mergeCloseHandlers(stream, closeHandlers));
    }

    @Override
    public Stream filter(final Predicate predicate) {
        return new IteratorStream<>(new ObjIteratorEx() {
            private boolean hasNext = false;
            private T next = null;

            @Override
            public boolean hasNext() {
                if (hasNext == false) {
                    while (elements.hasNext()) {
                        next = elements.next();

                        if (predicate.test(next)) {
                            hasNext = true;
                            break;
                        }
                    }
                }

                return hasNext;
            }

            @Override
            public T next() {
                if (hasNext == false && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                hasNext = false;

                return next;
            }
        }, sorted, cmp, closeHandlers);
    }

    @Override
    public Stream takeWhile(final Predicate predicate) {
        return new IteratorStream<>(new ObjIteratorEx() {
            private boolean hasMore = true;
            private boolean hasNext = false;
            private T next = null;

            @Override
            public boolean hasNext() {
                if (hasNext == false && hasMore && elements.hasNext()) {
                    next = elements.next();

                    if (predicate.test(next)) {
                        hasNext = true;
                    } else {
                        hasMore = false;
                    }
                }

                return hasNext;
            }

            @Override
            public T next() {
                if (hasNext == false && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                hasNext = false;

                return next;
            }

        }, sorted, cmp, closeHandlers);
    }

    @Override
    public Stream dropWhile(final Predicate predicate) {
        return new IteratorStream<>(new ObjIteratorEx() {
            private boolean hasNext = false;
            private T next = null;
            private boolean dropped = false;

            @Override
            public boolean hasNext() {
                if (hasNext == false) {
                    if (dropped == false) {
                        while (elements.hasNext()) {
                            next = elements.next();

                            if (predicate.test(next) == false) {
                                hasNext = true;
                                break;
                            }
                        }

                        dropped = true;
                    } else if (elements.hasNext()) {
                        next = elements.next();
                        hasNext = true;
                    }
                }

                return hasNext;
            }

            @Override
            public T next() {
                if (hasNext == false && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                hasNext = false;

                return next;
            }

        }, sorted, cmp, closeHandlers);
    }

    @Override
    public  Stream map(final Function mapper) {
        return new IteratorStream<>(new ObjIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public R next() {
                return mapper.apply(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    //    @Override
    //    public  Stream biMap(final BiFunction mapper, final boolean ignoreNotPaired) {
    //        return new IteratorStream<>(new ObjIteratorEx() {
    //            private T pre = (T) NONE;
    //
    //            @Override
    //            public boolean hasNext() {
    //                if (ignoreNotPaired && pre == NONE) {
    //                    if (elements.hasNext()) {
    //                        pre = elements.next();
    //                    } else {
    //                        return false;
    //                    }
    //                }
    //
    //                return elements.hasNext();
    //            }
    //
    //            @Override
    //            public R next() {
    //                if (!hasNext()) {
    //                    throw new NoSuchElementException();
    //                }
    //
    //                if (ignoreNotPaired) {
    //                    final R res = mapper.apply(pre, elements.next());
    //                    pre = (T) NONE;
    //                    return res;
    //                } else {
    //                    return mapper.apply(elements.next(), elements.hasNext() ? elements.next() : null);
    //                }
    //            }
    //
    //            //            @Override
    //            //            public void skip(long n) {
    //            //                elements.skip(n >= Long.MAX_VALUE / 2 ? Long.MAX_VALUE : n * 2);
    //            //            }
    //            //
    //            //            @Override
    //            //            public long count() {
    //            //                final long count = elements.count();
    //            //                return count % 2 == 0 || ignoreNotPaired ? count / 2 : count / 2 + 1;
    //            //            }
    //        }, closeHandlers);
    //    }
    //
    //    @Override
    //    public  Stream triMap(final TriFunction mapper, final boolean ignoreNotPaired) {
    //        return new IteratorStream<>(new ObjIteratorEx() {
    //            private T prepre = (T) NONE;
    //            private T pre = (T) NONE;
    //
    //            @Override
    //            public boolean hasNext() {
    //                if (ignoreNotPaired && pre == NONE) {
    //                    if (elements.hasNext()) {
    //                        prepre = elements.next();
    //
    //                        if (elements.hasNext()) {
    //                            pre = elements.next();
    //                        } else {
    //                            return false;
    //                        }
    //                    } else {
    //                        return false;
    //                    }
    //                }
    //
    //                return elements.hasNext();
    //            }
    //
    //            @Override
    //            public R next() {
    //                if (!hasNext()) {
    //                    throw new NoSuchElementException();
    //                }
    //
    //                if (ignoreNotPaired) {
    //                    final R res = mapper.apply(prepre, pre, elements.next());
    //                    prepre = (T) NONE;
    //                    pre = (T) NONE;
    //                    return res;
    //                } else {
    //                    return mapper.apply(elements.next(), elements.hasNext() ? elements.next() : null, elements.hasNext() ? elements.next() : null);
    //                }
    //            }
    //
    //            //            @Override
    //            //            public void skip(long n) {
    //            //                elements.skip(n >= Long.MAX_VALUE / 3 ? Long.MAX_VALUE : n * 3);
    //            //            }
    //            //
    //            //            @Override
    //            //            public long count() {
    //            //                final long count = elements.count();
    //            //                return count % 3 == 0 || ignoreNotPaired ? count / 3 : count / 3 + 1;
    //            //            }
    //        }, closeHandlers);
    //    }

    @Override
    public  Stream slidingMap(final BiFunction mapper, final int increment, final boolean ignoreNotPaired) {
        final int windowSize = 2;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        return new IteratorStream<>(new ObjIteratorEx() {
            @SuppressWarnings("unchecked")
            private final T NONE = (T) Stream.NONE;
            private T prev = NONE;
            private T _1 = NONE;

            @Override
            public boolean hasNext() {
                if (increment > windowSize && prev != NONE) {
                    int skipNum = increment - windowSize;

                    while (skipNum-- > 0 && elements.hasNext()) {
                        elements.next();
                    }

                    prev = NONE;
                }

                if (ignoreNotPaired && _1 == NONE && elements.hasNext()) {
                    _1 = elements.next();
                }

                return elements.hasNext();
            }

            @Override
            public R next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                if (ignoreNotPaired) {
                    final R res = mapper.apply(_1, (prev = elements.next()));
                    _1 = increment == 1 ? prev : NONE;
                    return res;
                } else {
                    if (increment == 1) {
                        return mapper.apply(prev == NONE ? elements.next() : prev, (prev = (elements.hasNext() ? elements.next() : null)));
                    } else {
                        return mapper.apply(elements.next(), (prev = (elements.hasNext() ? elements.next() : null)));
                    }
                }
            }
        }, closeHandlers);
    }

    @Override
    public  Stream slidingMap(final TriFunction mapper, final int increment, final boolean ignoreNotPaired) {
        final int windowSize = 3;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        return new IteratorStream<>(new ObjIteratorEx() {
            @SuppressWarnings("unchecked")
            private final T NONE = (T) Stream.NONE;
            private T prev = NONE;
            private T prev2 = NONE;
            private T _1 = NONE;
            private T _2 = NONE;

            @Override
            public boolean hasNext() {
                if (increment > windowSize && prev != NONE) {
                    int skipNum = increment - windowSize;

                    while (skipNum-- > 0 && elements.hasNext()) {
                        elements.next();
                    }

                    prev = NONE;
                }

                if (ignoreNotPaired) {
                    if (_1 == NONE && elements.hasNext()) {
                        _1 = elements.next();
                    }

                    if (_2 == NONE && elements.hasNext()) {
                        _2 = elements.next();
                    }
                }

                return elements.hasNext();
            }

            @Override
            public R next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                if (ignoreNotPaired) {
                    final R res = mapper.apply(_1, _2, (prev = elements.next()));
                    _1 = increment == 1 ? _2 : (increment == 2 ? prev : NONE);
                    _2 = increment == 1 ? prev : NONE;
                    return res;
                } else {
                    if (increment == 1) {
                        return mapper.apply(prev2 == NONE ? elements.next() : prev2,
                                (prev2 = (prev == NONE ? (elements.hasNext() ? elements.next() : null) : prev)),
                                (prev = (elements.hasNext() ? elements.next() : null)));

                    } else if (increment == 2) {
                        return mapper.apply(prev == NONE ? elements.next() : prev, (prev2 = (elements.hasNext() ? elements.next() : null)),
                                (prev = (elements.hasNext() ? elements.next() : null)));
                    } else {
                        return mapper.apply(elements.next(), (prev2 = (elements.hasNext() ? elements.next() : null)),
                                (prev = (elements.hasNext() ? elements.next() : null)));
                    }
                }
            }
        }, closeHandlers);
    }

    @Override
    public Stream mapFirst(final Function mapperForFirst) {
        N.requireNonNull(mapperForFirst);

        return new IteratorStream<>(new ObjIteratorEx() {
            private boolean isFirst = true;

            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public T next() {
                if (isFirst) {
                    isFirst = false;
                    return mapperForFirst.apply(elements.next());
                } else {
                    return elements.next();
                }
            }

            //            @Override
            //            public void skip(long n) {
            //                if (n > 0) {
            //                    isFirst = false;
            //                }
            //
            //                elements.skip(n);
            //            }
            //
            //            @Override
            //            public long count() {
            //                isFirst = false;
            //
            //                return elements.count();
            //            }

            @Override
            public void skip(long n) {
                if (n > 0) {
                    if (hasNext()) {
                        next();
                    }

                    elements.skip(n - 1);
                }
            }

            @Override
            public long count() {
                if (hasNext()) {
                    next();
                    return elements.count() + 1;
                }

                return 0;
            }
        }, closeHandlers);
    }

    @Override
    public  Stream mapFirstOrElse(final Function mapperForFirst, final Function mapperForElse) {
        N.requireNonNull(mapperForFirst);
        N.requireNonNull(mapperForElse);

        return new IteratorStream<>(new ObjIteratorEx() {
            private boolean isFirst = true;

            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public R next() {
                if (isFirst) {
                    isFirst = false;
                    return mapperForFirst.apply(elements.next());
                } else {
                    return mapperForElse.apply(elements.next());
                }
            }

            //            @Override
            //            public long count() {
            //                isFirst = false;
            //
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                if (n > 0) {
            //                    isFirst = false;
            //                }
            //
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public Stream mapLast(final Function mapperForLast) {
        N.requireNonNull(mapperForLast);

        return new IteratorStream<>(new ObjIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public T next() {
                final T next = elements.next();

                if (elements.hasNext()) {
                    return next;
                } else {
                    return mapperForLast.apply(next);
                }
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public  Stream mapLastOrElse(final Function mapperForLast, final Function mapperForElse) {
        N.requireNonNull(mapperForLast);
        N.requireNonNull(mapperForElse);

        return new IteratorStream<>(new ObjIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public R next() {
                final T next = elements.next();

                if (elements.hasNext()) {
                    return mapperForElse.apply(next);
                } else {
                    return mapperForLast.apply(next);
                }
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public CharStream mapToChar(final ToCharFunction mapper) {
        return new IteratorCharStream(new CharIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public char nextChar() {
                return mapper.applyAsChar(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public ByteStream mapToByte(final ToByteFunction mapper) {
        return new IteratorByteStream(new ByteIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public byte nextByte() {
                return mapper.applyAsByte(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public ShortStream mapToShort(final ToShortFunction mapper) {
        return new IteratorShortStream(new ShortIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public short nextShort() {
                return mapper.applyAsShort(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public IntStream mapToInt(final ToIntFunction mapper) {
        return new IteratorIntStream(new IntIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public int nextInt() {
                return mapper.applyAsInt(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public LongStream mapToLong(final ToLongFunction mapper) {
        return new IteratorLongStream(new LongIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public long nextLong() {
                return mapper.applyAsLong(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public FloatStream mapToFloat(final ToFloatFunction mapper) {
        return new IteratorFloatStream(new FloatIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public float nextFloat() {
                return mapper.applyAsFloat(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public DoubleStream mapToDouble(final ToDoubleFunction mapper) {
        return new IteratorDoubleStream(new DoubleIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public double nextDouble() {
                return mapper.applyAsDouble(elements.next());
            }

            //            @Override
            //            public long count() {
            //                return elements.count();
            //            }
            //
            //            @Override
            //            public void skip(long n) {
            //                elements.skip(n);
            //            }
        }, closeHandlers);
    }

    @Override
    public  Stream flatMap(final Function> mapper) {
        final ObjIteratorEx iter = new ObjIteratorEx() {
            private Iterator cur = null;
            private Stream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public R next() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.next();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorStream<>(iter, newCloseHandlers);
    }

    @Override
    public CharStream flatMapToChar(final Function mapper) {
        final CharIteratorEx iter = new CharIteratorEx() {
            private CharIterator cur = null;
            private CharStream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public char nextChar() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.nextChar();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorCharStream(iter, newCloseHandlers);
    }

    @Override
    public ByteStream flatMapToByte(final Function mapper) {
        final ByteIteratorEx iter = new ByteIteratorEx() {
            private ByteIterator cur = null;
            private ByteStream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public byte nextByte() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.nextByte();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorByteStream(iter, newCloseHandlers);
    }

    @Override
    public ShortStream flatMapToShort(final Function mapper) {
        final ShortIteratorEx iter = new ShortIteratorEx() {
            private ShortIterator cur = null;
            private ShortStream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public short nextShort() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.nextShort();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorShortStream(iter, newCloseHandlers);
    }

    @Override
    public IntStream flatMapToInt(final Function mapper) {
        final IntIteratorEx iter = new IntIteratorEx() {
            private IntIterator cur = null;
            private IntStream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public int nextInt() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.nextInt();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorIntStream(iter, newCloseHandlers);
    }

    @Override
    public LongStream flatMapToLong(final Function mapper) {
        final LongIteratorEx iter = new LongIteratorEx() {
            private LongIterator cur = null;
            private LongStream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public long nextLong() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.nextLong();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorLongStream(iter, newCloseHandlers);
    }

    @Override
    public FloatStream flatMapToFloat(final Function mapper) {
        final FloatIteratorEx iter = new FloatIteratorEx() {
            private FloatIterator cur = null;
            private FloatStream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public float nextFloat() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.nextFloat();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorFloatStream(iter, newCloseHandlers);
    }

    @Override
    public DoubleStream flatMapToDouble(final Function mapper) {
        final DoubleIteratorEx iter = new DoubleIteratorEx() {
            private DoubleIterator cur = null;
            private DoubleStream s = null;
            private Runnable closeHandle = null;

            @Override
            public boolean hasNext() {
                while ((cur == null || cur.hasNext() == false) && elements.hasNext()) {
                    if (closeHandle != null) {
                        final Runnable tmp = closeHandle;
                        closeHandle = null;
                        tmp.run();
                    }

                    s = mapper.apply(elements.next());

                    if (N.notNullOrEmpty(s.closeHandlers)) {
                        final Set tmp = s.closeHandlers;

                        closeHandle = new Runnable() {
                            @Override
                            public void run() {
                                Stream.close(tmp);
                            }
                        };
                    }

                    cur = s.iterator();
                }

                return cur != null && cur.hasNext();
            }

            @Override
            public double nextDouble() {
                if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                    throw new NoSuchElementException();
                }

                return cur.nextDouble();
            }

            @Override
            public void close() {
                if (closeHandle != null) {
                    final Runnable tmp = closeHandle;
                    closeHandle = null;
                    tmp.run();
                }
            }
        };

        final Set newCloseHandlers = N.isNullOrEmpty(closeHandlers) ? new LocalLinkedHashSet(1)
                : new LocalLinkedHashSet(closeHandlers);

        newCloseHandlers.add(new Runnable() {
            @Override
            public void run() {
                iter.close();
            }
        });

        return new IteratorDoubleStream(iter, newCloseHandlers);
    }

    @Override
    public Stream> splitToList(final int size) {
        N.checkArgument(size > 0, "'size' must be bigger than 0. Can't be: %s", size);

        return new IteratorStream<>(new ObjIteratorEx>() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public List next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                final List result = new ArrayList<>(size);
                int cnt = 0;

                while (cnt < size && elements.hasNext()) {
                    result.add(elements.next());
                    cnt++;
                }

                return result;
            }

            @Override
            public long count() {
                final long len = elements.count();
                return len % size == 0 ? len / size : len / size + 1;
            }

            @Override
            public void skip(long n) {
                elements.skip(n >= Long.MAX_VALUE / size ? Long.MAX_VALUE : n * size);
            }
        }, closeHandlers);
    }

    @Override
    public Stream> splitToSet(final int size) {
        N.checkArgument(size > 0, "'size' must be bigger than 0. Can't be: %s", size);

        return new IteratorStream<>(new ObjIteratorEx>() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public Set next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                final Set result = new HashSet<>(N.min(9, size));
                int cnt = 0;

                while (cnt < size && elements.hasNext()) {
                    result.add(elements.next());
                    cnt++;
                }

                return result;
            }

            @Override
            public long count() {
                final long len = elements.count();
                return len % size == 0 ? len / size : len / size + 1;
            }

            @Override
            public void skip(long n) {
                elements.skip(n >= Long.MAX_VALUE / size ? Long.MAX_VALUE : n * size);
            }
        }, closeHandlers);
    }

    @Override
    public Stream> splitToList(final Predicate predicate) {
        return new IteratorStream<>(new ObjIteratorEx>() {
            private T next = (T) NONE;
            private boolean preCondition = false;

            @Override
            public boolean hasNext() {
                return next != NONE || elements.hasNext();
            }

            @Override
            public List next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                final List result = new ArrayList<>();

                if (next == NONE) {
                    next = elements.next();
                }

                while (next != NONE) {
                    if (result.size() == 0) {
                        result.add(next);
                        preCondition = predicate.test(next);
                        next = elements.hasNext() ? elements.next() : (T) NONE;
                    } else if (predicate.test(next) == preCondition) {
                        result.add(next);
                        next = elements.hasNext() ? elements.next() : (T) NONE;
                    } else {

                        break;
                    }
                }

                return result;
            }

        }, closeHandlers);
    }

    @Override
    public  Stream> splitToList(final U seed, final BiPredicate predicate, final Consumer seedUpdate) {
        return new IteratorStream<>(new ObjIteratorEx>() {
            private T next = (T) NONE;
            private boolean preCondition = false;

            @Override
            public boolean hasNext() {
                return next != NONE || elements.hasNext();
            }

            @Override
            public List next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                final List result = new ArrayList<>();

                if (next == NONE) {
                    next = elements.next();
                }

                while (next != NONE) {
                    if (result.size() == 0) {
                        result.add(next);
                        preCondition = predicate.test(next, seed);
                        next = elements.hasNext() ? elements.next() : (T) NONE;
                    } else if (predicate.test(next, seed) == preCondition) {
                        result.add(next);
                        next = elements.hasNext() ? elements.next() : (T) NONE;
                    } else {
                        if (seedUpdate != null) {
                            seedUpdate.accept(seed);
                        }

                        break;
                    }
                }

                return result;
            }

        }, closeHandlers);
    }

    @Override
    public  Stream> splitToSet(final U seed, final BiPredicate predicate, final Consumer seedUpdate) {
        return new IteratorStream<>(new ObjIteratorEx>() {
            private T next = (T) NONE;
            private boolean preCondition = false;

            @Override
            public boolean hasNext() {
                return next != NONE || elements.hasNext();
            }

            @Override
            public Set next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                final Set result = new HashSet<>();

                if (next == NONE) {
                    next = elements.next();
                }

                while (next != NONE) {
                    if (result.size() == 0) {
                        result.add(next);
                        preCondition = predicate.test(next, seed);
                        next = elements.hasNext() ? elements.next() : (T) NONE;
                    } else if (predicate.test(next, seed) == preCondition) {
                        result.add(next);
                        next = elements.hasNext() ? elements.next() : (T) NONE;
                    } else {
                        if (seedUpdate != null) {
                            seedUpdate.accept(seed);
                        }

                        break;
                    }
                }

                return result;
            }

        }, closeHandlers);
    }

    @Override
    public Stream> slidingToList(final int windowSize, final int increment) {
        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        return new IteratorStream<>(new ObjIteratorEx>() {
            private List prev = null;

            @Override
            public boolean hasNext() {
                if (prev != null && increment > windowSize) {
                    int skipNum = increment - windowSize;

                    while (skipNum-- > 0 && elements.hasNext()) {
                        elements.next();
                    }

                    prev = null;
                }

                return elements.hasNext();
            }

            @Override
            public List next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                final List result = new ArrayList<>(windowSize);
                int cnt = 0;

                if (prev != null && increment < windowSize) {
                    cnt = windowSize - increment;

                    if (cnt <= 8) {
                        for (int i = windowSize - cnt; i < windowSize; i++) {
                            result.add(prev.get(i));
                        }
                    } else {
                        result.addAll(prev.subList(windowSize - cnt, windowSize));
                    }
                }

                while (cnt++ < windowSize && elements.hasNext()) {
                    result.add(elements.next());
                }

                return prev = result;
            }
        }, closeHandlers);
    }

    @Override
    public Stream top(int n) {
        return top(n, OBJECT_COMPARATOR);
    }

    @Override
    public Stream top(final int n, final Comparator comparator) {
        N.checkArgument(n > 0, "'n' must be bigger than 0");

        return new IteratorStream<>(new ObjIteratorEx() {
            T[] a = null;
            int cursor = 0;
            int toIndex;

            @Override
            public boolean hasNext() {
                if (a == null) {
                    top();
                }

                return cursor < toIndex;
            }

            @Override
            public T next() {
                if (a == null) {
                    top();
                }

                if (cursor >= toIndex) {
                    throw new NoSuchElementException();
                }

                return a[cursor++];
            }

            @Override
            public long count() {
                if (a == null) {
                    top();
                }

                return toIndex - cursor;
            }

            @Override
            public void skip(long n) {
                if (a == null) {
                    top();
                }

                cursor = n < toIndex - cursor ? cursor + (int) n : toIndex;
            }

            @Override
            public  A[] toArray(A[] b) {
                if (a == null) {
                    top();
                }

                b = b.length >= toIndex - cursor ? b : (A[]) N.newArray(b.getClass().getComponentType(), toIndex - cursor);

                N.copy(a, cursor, b, 0, toIndex - cursor);

                return b;
            }

            private void top() {
                if (sorted && isSameComparator(comparator, cmp)) {
                    final LinkedList queue = new LinkedList<>();

                    while (elements.hasNext()) {
                        if (queue.size() >= n) {
                            queue.poll();
                        }

                        queue.offer(elements.next());
                    }

                    a = (T[]) queue.toArray();
                } else {
                    final Comparator> pairCmp = new Comparator>() {
                        @Override
                        public int compare(final Indexed o1, final Indexed o2) {
                            return comparator.compare(o1.value(), o2.value());
                        }
                    };

                    final Queue> heap = new PriorityQueue<>(n, pairCmp);

                    Indexed pair = null;
                    for (long i = 0; elements.hasNext(); i++) {
                        pair = Indexed.of(elements.next(), i);

                        if (heap.size() >= n) {
                            if (pairCmp.compare(pair, heap.peek()) > 0) {
                                heap.poll();
                                heap.offer(pair);
                            }
                        } else {
                            heap.offer(pair);
                        }
                    }

                    final Indexed[] arrayOfPair = heap.toArray(new Indexed[heap.size()]);

                    N.sort(arrayOfPair, new Comparator>() {
                        @Override
                        public int compare(final Indexed o1, final Indexed o2) {
                            return N.compare(o1.longIndex(), o2.longIndex());
                        }
                    });

                    a = (T[]) new Object[arrayOfPair.length];

                    for (int i = 0, len = arrayOfPair.length; i < len; i++) {
                        a[i] = arrayOfPair[i].value();
                    }
                }

                toIndex = a.length;
            }
        }, sorted, cmp, closeHandlers);
    }

    @Override
    public Stream sorted() {
        return sorted(OBJECT_COMPARATOR);
    }

    @Override
    public Stream sorted(final Comparator comparator) {
        if (sorted && isSameComparator(comparator, cmp)) {
            return this;
        }

        return new IteratorStream<>(new ObjIteratorEx() {
            T[] a = null;
            int toIndex = 0;
            int cursor = 0;

            @Override
            public boolean hasNext() {
                if (a == null) {
                    sort();
                }

                return cursor < toIndex;
            }

            @Override
            public T next() {
                if (a == null) {
                    sort();
                }

                if (cursor >= toIndex) {
                    throw new NoSuchElementException();
                }

                return a[cursor++];
            }

            @Override
            public long count() {
                if (a == null) {
                    sort();
                }

                return toIndex - cursor;
            }

            @Override
            public void skip(long n) {
                if (a == null) {
                    sort();
                }

                cursor = n < toIndex - cursor ? cursor + (int) n : toIndex;
            }

            @Override
            public  A[] toArray(A[] b) {
                if (a == null) {
                    sort();
                }

                if (b.getClass().equals(a.getClass()) && b.length < toIndex - cursor) {
                    if (cursor == 0) {
                        return (A[]) a;
                    } else {
                        return (A[]) N.copyOfRange(a, cursor, toIndex);
                    }
                } else {
                    if (b.length < toIndex - cursor) {
                        b = N.newArray(b.getClass().getComponentType(), toIndex - cursor);
                    }

                    N.copy(a, cursor, b, 0, toIndex - cursor);

                    return b;
                }
            }

            private void sort() {
                a = (T[]) elements.toArray(N.EMPTY_OBJECT_ARRAY);
                toIndex = a.length;

                if (comparator == null) {
                    N.sort(a);
                } else {
                    N.sort(a, comparator);
                }
            }
        }, true, comparator, closeHandlers);
    }

    @Override
    public Stream peek(final Consumer action) {
        return new IteratorStream<>(new ObjIteratorEx() {
            @Override
            public boolean hasNext() {
                return elements.hasNext();
            }

            @Override
            public T next() {
                final T next = elements.next();
                action.accept(next);
                return next;
            }
        }, sorted, cmp, closeHandlers);
    }

    @Override
    public Stream limit(final long maxSize) {
        N.checkArgument(maxSize >= 0, "'maxSizse' can't be negative: %s", maxSize);

        return new IteratorStream<>(new ObjIteratorEx() {
            private long cnt = 0;

            @Override
            public boolean hasNext() {
                return cnt < maxSize && elements.hasNext();
            }

            @Override
            public T next() {
                if (cnt >= maxSize) {
                    throw new NoSuchElementException();
                }

                cnt++;
                return elements.next();
            }

            @Override
            public void skip(long n) {
                elements.skip(n);
            }
        }, sorted, cmp, closeHandlers);
    }

    @Override
    public Stream skip(final long n) {
        N.checkArgument(n >= 0, "'n' can't be negative: %s", n);

        if (n == 0) {
            return this;
        }

        return new IteratorStream<>(new ObjIteratorEx() {
            private boolean skipped = false;

            @Override
            public boolean hasNext() {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.hasNext();
            }

            @Override
            public T next() {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.next();
            }

            @Override
            public long count() {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.count();
            }

            @Override
            public void skip(long n2) {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                elements.skip(n2);
            }

            @Override
            public  A[] toArray(A[] a) {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.toArray(a);
            }
        }, sorted, cmp, closeHandlers);
    }

    @Override
    public  void forEach(Try.Consumer action) throws E {
        while (elements.hasNext()) {
            action.accept(elements.next());
        }
    }

    @Override
    public  R forEach(R seed, Try.BiFunction accumulator,
            Try.BiPredicate conditionToBreak) throws E, E2 {
        R result = seed;
        T next = null;

        while (elements.hasNext()) {
            next = elements.next();
            result = accumulator.apply(result, next);

            if (conditionToBreak.test(result, next)) {
                break;
            }
        }

        return result;
    }

    @Override
    public  void forEachPair(final Try.BiConsumer action, final int increment) throws E {
        final int windowSize = 2;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        T prev = (T) NONE;

        while (elements.hasNext()) {
            if (increment > windowSize && prev != NONE) {
                int skipNum = increment - windowSize;

                while (skipNum-- > 0 && elements.hasNext()) {
                    elements.next();
                }

                if (elements.hasNext() == false) {
                    break;
                }

                prev = (T) NONE;
            }

            if (increment == 1) {
                action.accept(prev == NONE ? elements.next() : prev, (prev = (elements.hasNext() ? elements.next() : null)));
            } else {
                action.accept(elements.next(), (prev = (elements.hasNext() ? elements.next() : null)));
            }
        }
    }

    @Override
    public  void forEachTriple(final Try.TriConsumer action, final int increment) throws E {
        final int windowSize = 3;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        T prev = (T) NONE;
        T prev2 = (T) NONE;

        while (elements.hasNext()) {
            if (increment > windowSize && prev != NONE) {
                int skipNum = increment - windowSize;

                while (skipNum-- > 0 && elements.hasNext()) {
                    elements.next();
                }

                if (elements.hasNext() == false) {
                    break;
                }

                prev = (T) NONE;
            }

            if (increment == 1) {
                action.accept(prev2 == NONE ? elements.next() : prev2, (prev2 = (prev == NONE ? (elements.hasNext() ? elements.next() : null) : prev)),
                        (prev = (elements.hasNext() ? elements.next() : null)));

            } else if (increment == 2) {
                action.accept(prev == NONE ? elements.next() : prev, (prev2 = (elements.hasNext() ? elements.next() : null)),
                        (prev = (elements.hasNext() ? elements.next() : null)));
            } else {
                action.accept(elements.next(), (prev2 = (elements.hasNext() ? elements.next() : null)), (prev = (elements.hasNext() ? elements.next() : null)));
            }
        }
    }

    @Override
    public Object[] toArray() {
        return toArray(N.EMPTY_OBJECT_ARRAY);
    }

     A[] toArray(A[] a) {
        return elements.toArray(a);
    }

    @Override
    public List toList() {
        final List result = new ArrayList<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public > R toList(Supplier supplier) {
        final R result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public Set toSet() {
        final Set result = new HashSet<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public > R toSet(Supplier supplier) {
        final R result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public Multiset toMultiset() {
        final Multiset result = new Multiset<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public Multiset toMultiset(Supplier> supplier) {
        final Multiset result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public LongMultiset toLongMultiset() {
        final LongMultiset result = new LongMultiset<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public LongMultiset toLongMultiset(Supplier> supplier) {
        final LongMultiset result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public > M toMap(Function keyExtractor, Function valueMapper,
            BinaryOperator mergeFunction, Supplier mapFactory) {
        final M result = mapFactory.get();
        T element = null;

        while (elements.hasNext()) {
            element = elements.next();
            Collectors.merge(result, keyExtractor.apply(element), valueMapper.apply(element), mergeFunction);
        }

        return result;
    }

    @Override
    public > M toMap(final Function classifier, final Collector downstream,
            final Supplier mapFactory) {
        final M result = mapFactory.get();
        final Supplier downstreamSupplier = downstream.supplier();
        final BiConsumer downstreamAccumulator = downstream.accumulator();
        final Map intermediate = (Map) result;
        K key = null;
        A v = null;
        T element = null;

        while (elements.hasNext()) {
            element = elements.next();
            key = N.requireNonNull(classifier.apply(element), "element cannot be mapped to a null key");

            if ((v = intermediate.get(key)) == null) {
                if ((v = downstreamSupplier.get()) != null) {
                    intermediate.put(key, v);
                }
            }

            downstreamAccumulator.accept(v, element);
        }

        final BiFunction function = new BiFunction() {
            @Override
            public A apply(K k, A v) {
                return (A) downstream.finisher().apply(v);
            }
        };

        Collectors.replaceAll(intermediate, function);

        return result;
    }

    @Override
    public > M toMap(final Function classifier, final Function valueMapper,
            final Collector downstream, final Supplier mapFactory) {
        final M result = mapFactory.get();
        final Supplier downstreamSupplier = downstream.supplier();
        final BiConsumer downstreamAccumulator = downstream.accumulator();
        final Map intermediate = (Map) result;
        K key = null;
        A v = null;
        T element = null;

        while (elements.hasNext()) {
            element = elements.next();
            key = N.requireNonNull(classifier.apply(element), "element cannot be mapped to a null key");

            if ((v = intermediate.get(key)) == null) {
                if ((v = downstreamSupplier.get()) != null) {
                    intermediate.put(key, v);
                }
            }

            downstreamAccumulator.accept(v, valueMapper.apply(element));
        }

        final BiFunction function = new BiFunction() {
            @Override
            public A apply(K k, A v) {
                return (A) downstream.finisher().apply(v);
            }
        };

        Collectors.replaceAll(intermediate, function);

        return result;
    }

    @Override
    public , M extends Multimap> M toMultimap(Function keyExtractor,
            Function valueMapper, Supplier mapFactory) {
        final M result = mapFactory.get();
        T element = null;

        while (elements.hasNext()) {
            element = elements.next();
            result.put(keyExtractor.apply(element), valueMapper.apply(element));
        }

        return result;
    }

    @Override
    public T reduce(T identity, BinaryOperator accumulator) {
        T result = identity;

        while (elements.hasNext()) {
            result = accumulator.apply(result, elements.next());
        }

        return result;
    }

    @Override
    public Nullable reduce(BinaryOperator accumulator) {
        if (elements.hasNext() == false) {
            return Nullable.empty();
        }

        T result = elements.next();

        while (elements.hasNext()) {
            result = accumulator.apply(result, elements.next());
        }

        return Nullable.of(result);
    }

    @Override
    public  U reduce(U identity, BiFunction accumulator, BinaryOperator combiner) {
        U result = identity;

        while (elements.hasNext()) {
            result = accumulator.apply(result, elements.next());
        }

        return result;
    }

    @Override
    public  R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner) {
        final R result = supplier.get();

        while (elements.hasNext()) {
            accumulator.accept(result, elements.next());
        }

        return result;
    }

    @Override
    public  R collect(Collector collector) {
        final A container = collector.supplier().get();
        final BiConsumer accumulator = collector.accumulator();

        while (elements.hasNext()) {
            accumulator.accept(container, elements.next());
        }

        return collector.finisher().apply(container);
    }

    @Override
    public Nullable head() {
        if (head == null) {
            head = elements.hasNext() ? Nullable.of(elements.next()) : Nullable. empty();
            tail = new IteratorStream<>(elements, sorted, cmp, closeHandlers);
        }

        return head;
    }

    @Override
    public Stream tail() {
        if (tail == null) {
            head = elements.hasNext() ? Nullable.of(elements.next()) : Nullable. empty();
            tail = new IteratorStream<>(elements, sorted, cmp, closeHandlers);
        }

        return tail;
    }

    @Override
    public Stream headd() {
        if (head2 == null) {
            final Object[] a = this.toArray();
            head2 = new ArrayStream<>((T[]) a, 0, a.length == 0 ? 0 : a.length - 1, sorted, cmp, closeHandlers);
            tail2 = a.length == 0 ? Nullable. empty() : Nullable.of((T) a[a.length - 1]);
        }

        return head2;
    }

    @Override
    public Nullable taill() {
        if (tail2 == null) {
            final Object[] a = this.toArray();
            head2 = new ArrayStream<>((T[]) a, 0, a.length == 0 ? 0 : a.length - 1, sorted, cmp, closeHandlers);
            tail2 = a.length == 0 ? Nullable. empty() : Nullable.of((T) a[a.length - 1]);
        }

        return tail2;
    }

    @Override
    public Stream last(final int n) {
        N.checkArgument(n >= 0, "'n' can't be negative: %s", n);

        if (n == 0) {
            return new IteratorStream<>(ObjIteratorEx.EMPTY, sorted, cmp, closeHandlers);
        }

        final Deque dqueue = n <= 1024 ? new ArrayDeque(n) : new LinkedList();

        while (elements.hasNext()) {
            if (dqueue.size() >= n) {
                dqueue.pollFirst();
            }

            dqueue.offerLast(elements.next());
        }

        return new IteratorStream<>(dqueue.iterator(), sorted, cmp, closeHandlers);
    }

    @Override
    public Stream skipLast(final int n) {
        N.checkArgument(n >= 0, "'n' can't be negative: %s", n);

        if (n == 0) {
            return this;
        }

        return new IteratorStream<>(new ObjIteratorEx() {
            private Deque dqueue = null;

            @Override
            public boolean hasNext() {
                if (dqueue == null) {
                    dqueue = n <= 1024 ? new ArrayDeque(n) : new LinkedList();

                    while (dqueue.size() < n && elements.hasNext()) {
                        dqueue.offerLast(elements.next());
                    }
                }

                return elements.hasNext();
            }

            @Override
            public T next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                dqueue.offerLast(elements.next());

                return dqueue.pollFirst();
            }

        }, sorted, cmp, closeHandlers);
    }

    @Override
    public Nullable min(Comparator comparator) {
        if (elements.hasNext() == false) {
            return Nullable.empty();
        } else if (sorted && isSameComparator(comparator, cmp)) {
            return Nullable.of(elements.next());
        }

        comparator = comparator == null ? OBJECT_COMPARATOR : comparator;
        T candidate = elements.next();
        T next = null;

        while (elements.hasNext()) {
            next = elements.next();
            if (comparator.compare(next, candidate) < 0) {
                candidate = next;
            }
        }

        return Nullable.of(candidate);
    }

    @Override
    public Nullable max(Comparator comparator) {
        if (elements.hasNext() == false) {
            return Nullable.empty();
        } else if (sorted && isSameComparator(comparator, cmp)) {
            T next = null;

            while (elements.hasNext()) {
                next = elements.next();
            }

            return Nullable.of(next);
        }

        comparator = comparator == null ? OBJECT_COMPARATOR : comparator;
        T candidate = elements.next();
        T next = null;

        while (elements.hasNext()) {
            next = elements.next();
            if (comparator.compare(next, candidate) > 0) {
                candidate = next;
            }
        }

        return Nullable.of(candidate);
    }

    @Override
    public Nullable kthLargest(int k, Comparator comparator) {
        N.checkArgument(k > 0, "'k' must be bigger than 0");

        if (elements.hasNext() == false) {
            return Nullable.empty();
        } else if (sorted && isSameComparator(comparator, cmp)) {
            final LinkedList queue = new LinkedList<>();

            while (elements.hasNext()) {
                if (queue.size() >= k) {
                    queue.poll();
                }

                queue.offer(elements.next());
            }

            return queue.size() < k ? (Nullable) Nullable.empty() : Nullable.of(queue.peek());
        }

        comparator = comparator == null ? OBJECT_COMPARATOR : comparator;
        final Queue queue = new PriorityQueue<>(k, comparator);
        T e = null;

        while (elements.hasNext()) {
            e = elements.next();

            if (queue.size() < k) {
                queue.offer(e);
            } else {
                if (comparator.compare(e, queue.peek()) > 0) {
                    queue.poll();
                    queue.offer(e);
                }
            }
        }

        return queue.size() < k ? (Nullable) Nullable.empty() : Nullable.of(queue.peek());
    }

    @Override
    public long count() {
        return elements.count();
    }

    @Override
    public  boolean anyMatch(final Try.Predicate predicate) throws E {
        while (elements.hasNext()) {
            if (predicate.test(elements.next())) {
                return true;
            }
        }

        return false;
    }

    @Override
    public  boolean allMatch(final Try.Predicate predicate) throws E {
        while (elements.hasNext()) {
            if (predicate.test(elements.next()) == false) {
                return false;
            }
        }

        return true;
    }

    @Override
    public  boolean noneMatch(final Try.Predicate predicate) throws E {
        while (elements.hasNext()) {
            if (predicate.test(elements.next())) {
                return false;
            }
        }

        return true;
    }

    @Override
    public  Nullable findFirst(final Try.Predicate predicate) throws E {
        while (elements.hasNext()) {
            T e = elements.next();

            if (predicate.test(e)) {
                return Nullable.of(e);
            }
        }

        return (Nullable) Nullable.empty();
    }

    @Override
    public  Nullable findLast(final Try.Predicate predicate) throws E {
        if (elements.hasNext() == false) {
            return (Nullable) Nullable.empty();
        }

        boolean hasResult = false;
        T e = null;
        T result = null;

        while (elements.hasNext()) {
            e = elements.next();

            if (predicate.test(e)) {
                result = e;
                hasResult = true;
            }
        }

        return hasResult ? Nullable.of(result) : (Nullable) Nullable.empty();
    }

    /**
     * Returns a Stream with elements from a temporary queue which is filled by reading the elements from the specified iterator asynchronously.
     * 
     * @param stream
     * @param queueSize Default value is 8
     * @return
     */
    @Override
    public Stream queued(int queueSize) {
        final Iterator iter = iterator();

        if (iter instanceof QueuedIterator && ((QueuedIterator) iter).max() >= queueSize) {
            return this;
        } else {
            return new IteratorStream<>(Stream.parallelConcatt(Arrays.asList(iter), 1, queueSize), sorted, cmp, closeHandlers);
        }
    }

    @Override
    ObjIteratorEx iteratorEx() {
        return elements;
    }

    @Override
    public Stream parallel(int maxThreadNum, Splitor splitor) {
        return new ParallelIteratorStream<>(elements, sorted, cmp, maxThreadNum, splitor, closeHandlers);
    }

    @Override
    public Stream onClose(Runnable closeHandler) {
        final Set newCloseHandlers = new LocalLinkedHashSet<>(N.isNullOrEmpty(this.closeHandlers) ? 1 : this.closeHandlers.size() + 1);

        if (N.notNullOrEmpty(this.closeHandlers)) {
            newCloseHandlers.addAll(this.closeHandlers);
        }

        newCloseHandlers.add(closeHandler);

        return new IteratorStream<>(elements, sorted, cmp, newCloseHandlers);
    }
}