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

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

Go to download

A general programming library in Java/Android. It's easy to learn and simple to use with concise and powerful APIs.

There is a newer version: 5.3.16
Show newest version
/*
 * Copyright (C) 2016, 2017, 2018, 2019 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.Collection;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import com.landawn.abacus.exception.DuplicatedResultException;
import com.landawn.abacus.util.CharIterator;
import com.landawn.abacus.util.CharList;
import com.landawn.abacus.util.CharSummaryStatistics;
import com.landawn.abacus.util.Fn;
import com.landawn.abacus.util.Fn.Suppliers;
import com.landawn.abacus.util.IndexedChar;
import com.landawn.abacus.util.Joiner;
import com.landawn.abacus.util.MergeResult;
import com.landawn.abacus.util.Multiset;
import com.landawn.abacus.util.MutableChar;
import com.landawn.abacus.util.MutableInt;
import com.landawn.abacus.util.MutableLong;
import com.landawn.abacus.util.N;
import com.landawn.abacus.util.Pair;
import com.landawn.abacus.util.Percentage;
import com.landawn.abacus.util.StringUtil.Strings;
import com.landawn.abacus.util.Throwables;
import com.landawn.abacus.util.Tuple.Tuple3;
import com.landawn.abacus.util.u.Optional;
import com.landawn.abacus.util.u.OptionalChar;
import com.landawn.abacus.util.function.BiConsumer;
import com.landawn.abacus.util.function.BinaryOperator;
import com.landawn.abacus.util.function.CharBiFunction;
import com.landawn.abacus.util.function.CharBiPredicate;
import com.landawn.abacus.util.function.CharBinaryOperator;
import com.landawn.abacus.util.function.CharConsumer;
import com.landawn.abacus.util.function.CharFunction;
import com.landawn.abacus.util.function.CharPredicate;
import com.landawn.abacus.util.function.CharTernaryOperator;
import com.landawn.abacus.util.function.CharTriPredicate;
import com.landawn.abacus.util.function.Function;
import com.landawn.abacus.util.function.ObjCharConsumer;
import com.landawn.abacus.util.function.Supplier;
import com.landawn.abacus.util.function.ToCharFunction;

/**
 *
 */
abstract class AbstractCharStream extends CharStream {

    AbstractCharStream(final boolean sorted, final Collection closeHandlers) {
        super(sorted, closeHandlers);
    }

    @Override
    public CharStream distinct() {
        assertNotClosed();

        final Set set = N.newHashSet();

        return newStream(this.sequential().filter(value -> set.add(value)).iteratorEx(), sorted);
    }

    //    @Override
    //    public CharStream flattMap(final CharFunction mapper) {
    //        assertNotClosed();
    //
    //        return flatMap(new CharFunction() {
    //            @Override
    //            public CharStream apply(char t) {
    //                return CharStream.of(mapper.apply(t));
    //            }
    //        });
    //    }

    @Override
    public CharStream flattMap(final CharFunction mapper) {
        assertNotClosed();

        return flatMap(t -> CharStream.of(mapper.apply(t)));
    }

    @Override
    public  Stream flattMapToObj(final CharFunction> mapper) {
        assertNotClosed();

        return flatMapToObj(t -> Stream.of(mapper.apply(t)));
    }

    @Override
    public  Stream flatMappToObj(final CharFunction mapper) {
        assertNotClosed();

        return flatMapToObj(t -> Stream.of(mapper.apply(t)));
    }

    @Override
    public CharStream mapPartial(final CharFunction mapper) {
        if (isParallel()) {
            return mapToObj(mapper).psp(s -> s.filter(Fn.IS_PRESENT_CHAR).mapToChar(Fn.GET_AS_CHAR));
        } else {
            return mapToObj(mapper).filter(Fn.IS_PRESENT_CHAR).mapToChar(Fn.GET_AS_CHAR);
        }
    }

    @Override
    public CharStream rangeMap(final CharBiPredicate sameRange, final CharBinaryOperator mapper) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new CharIteratorEx() {
            private char left = 0, right = 0, next = 0;
            private boolean hasNext = false;

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

            @Override
            public char nextChar() {
                left = hasNext ? next : iter.nextChar();
                right = left;

                while (hasNext = iter.hasNext()) {
                    next = iter.nextChar();

                    if (sameRange.test(left, next)) {
                        right = next;
                    } else {
                        break;
                    }
                }

                return mapper.applyAsChar(left, right);
            }
        }, false);
    }

    @Override
    public  Stream rangeMapToObj(final CharBiPredicate sameRange, final CharBiFunction mapper) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new ObjIteratorEx() {
            private char left = 0, right = 0, next = 0;
            private boolean hasNext = false;

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

            @Override
            public T next() {
                left = hasNext ? next : iter.nextChar();
                right = left;

                while (hasNext = iter.hasNext()) {
                    next = iter.nextChar();

                    if (sameRange.test(left, next)) {
                        right = next;
                    } else {
                        break;
                    }
                }

                return mapper.apply(left, right);
            }
        }, false, null);
    }

    @Override
    public Stream collapse(final CharBiPredicate collapsible) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new ObjIteratorEx() {
            private boolean hasNext = false;
            private char next = 0;

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

            @Override
            public CharList next() {
                final CharList result = new CharList(9);
                result.add(hasNext ? next : (next = iter.nextChar()));

                while ((hasNext = iter.hasNext())) {
                    if (collapsible.test(next, (next = iter.nextChar()))) {
                        result.add(next);
                    } else {
                        break;
                    }
                }

                return result;
            }
        }, false, null);
    }

    @Override
    public CharStream collapse(final CharBiPredicate collapsible, final CharBinaryOperator mergeFunction) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new CharIteratorEx() {
            private boolean hasNext = false;
            private char next = 0;

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

            @Override
            public char nextChar() {
                char res = hasNext ? next : (next = iter.nextChar());

                while ((hasNext = iter.hasNext())) {
                    if (collapsible.test(next, (next = iter.nextChar()))) {
                        res = mergeFunction.applyAsChar(res, next);
                    } else {
                        break;
                    }
                }

                return res;
            }
        }, false);
    }

    @Override
    public CharStream collapse(final CharTriPredicate collapsible, final CharBinaryOperator mergeFunction) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new CharIteratorEx() {
            private boolean hasNext = false;
            private char next = 0;

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

            @Override
            public char nextChar() {
                final char first = hasNext ? next : (next = iter.nextChar());
                char res = first;

                while ((hasNext = iter.hasNext())) {
                    if (collapsible.test(first, next, (next = iter.nextChar()))) {
                        res = mergeFunction.applyAsChar(res, next);
                    } else {
                        break;
                    }
                }

                return res;
            }
        }, false);
    }

    @Override
    public CharStream skip(final long n, final CharConsumer action) {
        assertNotClosed();

        checkArgNotNegative(n, "n");
        checkArgNotNull(action, "action");

        final CharPredicate filter = isParallel() ? new CharPredicate() {
            final AtomicLong cnt = new AtomicLong(n);

            @Override
            public boolean test(char value) {
                return cnt.getAndDecrement() > 0;
            }
        } : new CharPredicate() {
            final MutableLong cnt = MutableLong.of(n);

            @Override
            public boolean test(char value) {
                return cnt.getAndDecrement() > 0;
            }
        };

        return dropWhile(filter, action);
    }

    @Override
    public CharStream removeIf(final CharPredicate predicate) {
        assertNotClosed();

        return filter(value -> !predicate.test(value));
    }

    @Override
    public CharStream removeIf(final CharPredicate predicate, final CharConsumer actionOnDroppedItem) {
        assertNotClosed();

        return filter(value -> {
            if (predicate.test(value)) {
                actionOnDroppedItem.accept(value);
                return false;
            }

            return true;
        });
    }

    @Override
    public CharStream filter(final CharPredicate predicate, final CharConsumer actionOnDroppedItem) {
        assertNotClosed();

        return filter(value -> {
            if (!predicate.test(value)) {
                actionOnDroppedItem.accept(value);
                return false;
            }

            return true;
        });
    }

    @Override
    public CharStream dropWhile(final CharPredicate predicate, final CharConsumer actionOnDroppedItem) {
        assertNotClosed();

        return dropWhile(value -> {
            if (predicate.test(value)) {
                actionOnDroppedItem.accept(value);
                return true;
            }

            return false;
        });
    }

    @Override
    public CharStream step(final long step) {
        assertNotClosed();

        checkArgPositive(step, "step");

        if (step == 1) {
            return skip(0);
        }

        final long skip = step - 1;
        final CharIteratorEx iter = this.iteratorEx();

        final CharIterator charIterator = new CharIteratorEx() {
            @Override
            public boolean hasNext() {
                return iter.hasNext();
            }

            @Override
            public char nextChar() {
                final char next = iter.nextChar();
                iter.advance(skip);
                return next;
            }
        };

        return newStream(charIterator, sorted);
    }

    @Override
    public Stream split(final int chunkSize) {
        assertNotClosed();

        return splitToList(chunkSize).map(t -> new ArrayCharStream(t.array(), 0, t.size(), sorted, null));
    }

    @Override
    public Stream split(final CharPredicate predicate) {
        assertNotClosed();

        return splitToList(predicate).map(t -> new ArrayCharStream(t.array(), 0, t.size(), sorted, null));
    }

    @Override
    public Stream splitAt(final CharPredicate where) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new ObjIteratorEx() {
            private int cursor = 0;
            private char next = 0;
            private boolean hasNext = false;

            @Override
            public boolean hasNext() {
                return cursor < 2;
            }

            @Override
            public CharStream next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }

                CharStream result = null;

                if (cursor == 0) {
                    final CharList list = new CharList();

                    while (iter.hasNext()) {
                        next = iter.nextChar();

                        if (!where.test(next)) {
                            list.add(next);
                        } else {
                            hasNext = true;
                            break;
                        }
                    }

                    result = new ArrayCharStream(list.array(), 0, list.size(), sorted, null);
                } else {
                    CharIteratorEx iterEx = iter;

                    if (hasNext) {
                        iterEx = new CharIteratorEx() {
                            private boolean isFirst = true;

                            @Override
                            public boolean hasNext() {
                                return isFirst || iter.hasNext();
                            }

                            @Override
                            public char nextChar() {
                                if (!hasNext()) {
                                    throw new NoSuchElementException();
                                }

                                if (isFirst) {
                                    isFirst = false;
                                    return next;
                                } else {
                                    return iter.nextChar();
                                }
                            }
                        };
                    }

                    result = new IteratorCharStream(iterEx, sorted, null);
                }

                cursor++;

                return result;
            }

            @Override
            public long count() {
                iter.count();

                return 2 - cursor;
            }

            @Override
            public void advance(long n) {
                if (n == 0) {
                    return;
                } else if (n == 1) {
                    if (cursor == 0) {
                        while (iter.hasNext()) {
                            next = iter.nextChar();

                            if (!where.test(next)) {
                                hasNext = true;
                                break;
                            }
                        }
                    } else {
                        iter.advance(Long.MAX_VALUE);
                    }
                } else {
                    iter.advance(Long.MAX_VALUE);
                }

                cursor = n >= 2 ? 2 : cursor + (int) n;
            }

        }, false, null);
    }

    @Override
    public Stream sliding(final int windowSize, final int increment) {
        assertNotClosed();

        return slidingToList(windowSize, increment).map(t -> new ArrayCharStream(t.array(), 0, t.size(), sorted, null));
    }

    @Override
    public CharStream scan(final CharBinaryOperator accumulator) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new CharIteratorEx() {
            private char res = 0;
            private boolean isFirst = true;

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

            @Override
            public char nextChar() {
                if (isFirst) {
                    isFirst = false;
                    return (res = iter.nextChar());
                } else {
                    return (res = accumulator.applyAsChar(res, iter.nextChar()));
                }
            }
        }, false);
    }

    @Override
    public CharStream scan(final char init, final CharBinaryOperator accumulator) {
        assertNotClosed();

        final CharIteratorEx iter = iteratorEx();

        return newStream(new CharIteratorEx() {
            private char res = init;

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

            @Override
            public char nextChar() {
                return (res = accumulator.applyAsChar(res, iter.nextChar()));
            }
        }, false);
    }

    @Override
    public CharStream scan(final char init, final CharBinaryOperator accumulator, final boolean initIncluded) {
        assertNotClosed();

        if (!initIncluded) {
            return scan(init, accumulator);
        }

        final CharIteratorEx iter = iteratorEx();

        return newStream(new CharIteratorEx() {
            private boolean isFirst = true;
            private char res = init;

            @Override
            public boolean hasNext() {
                return isFirst || iter.hasNext();
            }

            @Override
            public char nextChar() {
                if (isFirst) {
                    isFirst = false;
                    return init;
                }

                return (res = accumulator.applyAsChar(res, iter.nextChar()));
            }
        }, false);
    }

    @Override
    public CharStream intersection(final Collection c) {
        assertNotClosed();

        final Multiset multiset = Multiset.from(c);

        return newStream(this.sequential().filter(value -> multiset.getAndRemove(value) > 0).iteratorEx(), sorted);
    }

    @Override
    public CharStream difference(final Collection c) {
        assertNotClosed();

        final Multiset multiset = Multiset.from(c);

        return newStream(this.sequential().filter(value -> multiset.getAndRemove(value) < 1).iteratorEx(), sorted);
    }

    @Override
    public CharStream symmetricDifference(final Collection c) {
        assertNotClosed();

        final Multiset multiset = Multiset.from(c);

        return newStream(this.sequential()
                .filter(value -> multiset.getAndRemove(value) < 1)
                .append(Stream.of(c).filter(value -> multiset.getAndRemove(value) > 0).mapToChar(ToCharFunction.UNBOX))
                .iteratorEx(), false);
    }

    @Override
    public CharStream reversed() {
        assertNotClosed();

        return newStream(new CharIteratorEx() {
            private boolean initialized = false;

            private char[] elements;
            private int fromIndex = -1;
            private int toIndex = -1;

            private int cursor;

            @Override
            public boolean hasNext() {
                if (!initialized) {
                    init();
                }

                return cursor > fromIndex;
            }

            @Override
            public char nextChar() {
                if (!initialized) {
                    init();
                }

                if (cursor <= fromIndex) {
                    throw new NoSuchElementException();
                }

                return elements[--cursor];
            }

            @Override
            public long count() {
                if (!initialized) {
                    init();
                }

                return cursor - fromIndex;
            }

            @Override
            public void advance(long n) {
                if (!initialized) {
                    init();
                }

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

            @Override
            public char[] toArray() {
                if (!initialized) {
                    init();
                }

                final char[] a = new char[cursor - fromIndex];

                for (int i = 0, len = cursor - fromIndex; i < len; i++) {
                    a[i] = elements[cursor - i - 1];
                }

                return a;
            }

            private void init() {
                if (!initialized) {
                    initialized = true;

                    final Tuple3 tp = AbstractCharStream.this.arrayForIntermediateOp();

                    elements = tp._1;
                    fromIndex = tp._2;
                    toIndex = tp._3;

                    cursor = toIndex;
                }
            }
        }, false);
    }

    @Override
    public CharStream rotated(final int distance) {
        assertNotClosed();

        return newStream(new CharIteratorEx() {
            private boolean initialized = false;

            private char[] elements;
            private int fromIndex = -1;
            private int toIndex = -1;

            private int len;
            private int start;
            private int cnt = 0;

            @Override
            public boolean hasNext() {
                if (!initialized) {
                    init();
                }

                return cnt < len;
            }

            @Override
            public char nextChar() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }

                return elements[((start + cnt++) % len) + fromIndex];
            }

            @Override
            public long count() {
                if (!initialized) {
                    init();
                }

                return len - cnt;
            }

            @Override
            public void advance(long n) {
                if (!initialized) {
                    init();
                }

                cnt = n < len - cnt ? cnt + (int) n : len;
            }

            @Override
            public char[] toArray() {
                if (!initialized) {
                    init();
                }

                final char[] a = new char[len - cnt];

                for (int i = cnt; i < len; i++) {
                    a[i - cnt] = elements[((start + i) % len) + fromIndex];
                }

                return a;
            }

            private void init() {
                if (!initialized) {
                    initialized = true;

                    final Tuple3 tp = AbstractCharStream.this.arrayForIntermediateOp();

                    elements = tp._1;
                    fromIndex = tp._2;
                    toIndex = tp._3;

                    len = toIndex - fromIndex;

                    if (len > 0) {
                        start = distance % len;

                        if (start < 0) {
                            start += len;
                        }

                        start = len - start;
                    }
                }
            }
        }, distance == 0 && sorted);
    }

    @Override
    public CharStream shuffled(final Random rnd) {
        assertNotClosed();

        checkArgNotNull(rnd, "random");

        return lazyLoad(a -> {
            N.shuffle(a, rnd);
            return a;
        }, false);
    }

    @Override
    public CharStream sorted() {
        assertNotClosed();

        if (sorted) {
            return newStream(iteratorEx(), sorted);
        }

        return lazyLoad(a -> {
            if (isParallel()) {
                N.parallelSort(a);
            } else {
                N.sort(a);
            }

            return a;
        }, true);
    }

    @Override
    public CharStream reverseSorted() {
        assertNotClosed();

        return newStream(new CharIteratorEx() {
            private boolean initialized = false;
            private char[] aar;
            private int cursor;

            @Override
            public boolean hasNext() {
                if (!initialized) {
                    init();
                }

                return cursor > 0;
            }

            @Override
            public char nextChar() {
                if (!initialized) {
                    init();
                }

                if (cursor <= 0) {
                    throw new NoSuchElementException();
                }

                return aar[--cursor];
            }

            @Override
            public long count() {
                if (!initialized) {
                    init();
                }

                return cursor;
            }

            @Override
            public void advance(long n) {
                if (!initialized) {
                    init();
                }

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

            @Override
            public char[] toArray() {
                if (!initialized) {
                    init();
                }

                final char[] a = new char[cursor];

                for (int i = 0; i < cursor; i++) {
                    a[i] = aar[cursor - i - 1];
                }

                return a;
            }

            private void init() {
                if (!initialized) {
                    initialized = true;
                    aar = AbstractCharStream.this.toArrayForIntermediateOp();

                    if (isParallel()) {
                        N.parallelSort(aar);
                    } else {
                        N.sort(aar);
                    }

                    cursor = aar.length;
                }
            }
        }, false);
    }

    private CharStream lazyLoad(final Function op, final boolean sorted) {
        return newStream(new CharIteratorEx() {
            private boolean initialized = false;
            private char[] aar;
            private int cursor = 0;
            private int len;

            @Override
            public boolean hasNext() {
                if (!initialized) {
                    init();
                }

                return cursor < len;
            }

            @Override
            public char nextChar() {
                if (!initialized) {
                    init();
                }

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

                return aar[cursor++];
            }

            @Override
            public long count() {
                if (!initialized) {
                    init();
                }

                return len - cursor;
            }

            @Override
            public void advance(long n) {
                if (!initialized) {
                    init();
                }

                cursor = n > len - cursor ? len : cursor + (int) n;
            }

            @Override
            public char[] toArray() {
                if (!initialized) {
                    init();
                }

                final char[] a = new char[len - cursor];

                for (int i = cursor; i < len; i++) {
                    a[i - cursor] = aar[i];
                }

                return a;
            }

            private void init() {
                if (!initialized) {
                    initialized = true;
                    aar = op.apply(AbstractCharStream.this.toArrayForIntermediateOp());
                    len = aar.length;
                }
            }
        }, sorted);
    }

    @Override
    public CharStream cycled() {
        assertNotClosed();

        return newStream(new CharIterator() {
            private CharIterator iter = null;
            private CharList list = null;
            private char[] a = null;
            private int len = 0;
            private int cursor = -1;
            private char e = 0;

            private boolean initialized = false;

            @Override
            public boolean hasNext() {
                if (!initialized) {
                    init();
                }

                if (a == null && !iter.hasNext()) {
                    a = list.toArray();
                    len = a.length;
                    cursor = 0;
                }

                return cursor < len || iter.hasNext();
            }

            @Override
            public char nextChar() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }

                if (len > 0) {
                    if (cursor >= len) {
                        cursor = 0;
                    }

                    return a[cursor++];
                } else {
                    e = iter.nextChar();
                    list.add(e);

                    return e;
                }
            }

            private void init() {
                if (!initialized) {
                    initialized = true;
                    iter = AbstractCharStream.this.iteratorEx();
                    list = new CharList();
                }
            }
        }, false);
    }

    @Override
    public CharStream cycled(final long rounds) {
        assertNotClosed();

        checkArgNotNegative(rounds, "times");

        if (rounds == 0) {
            return limit(0);
        } else if (rounds == 1) {
            return skip(0);
        }

        return newStream(new CharIterator() {
            private CharIterator iter = null;
            private CharList list = null;
            private char[] a = null;
            private int len = 0;
            private int cursor = -1;
            private char e = 0;
            private long m = 0;

            private boolean initialized = false;

            @Override
            public boolean hasNext() {
                if (!initialized) {
                    init();
                }

                if (a == null && !iter.hasNext()) {
                    a = list.toArray();
                    len = a.length;
                    cursor = 0;
                    m = 1;
                }

                return m < rounds && (cursor < len || rounds - m > 1) && (len > 0 || iter.hasNext());
            }

            @Override
            public char nextChar() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }

                if (len > 0) {
                    if (cursor >= len) {
                        cursor = 0;
                        m++;
                    }

                    return a[cursor++];
                } else {
                    e = iter.nextChar();
                    list.add(e);

                    return e;
                }
            }

            private void init() {
                if (!initialized) {
                    initialized = true;
                    iter = AbstractCharStream.this.iteratorEx();
                    list = new CharList();
                }
            }
        }, rounds <= 1 ? this.sorted : false);
    }

    @Override
    public Stream indexed() {
        assertNotClosed();

        final MutableLong idx = MutableLong.of(0);

        return newStream(this.sequential().mapToObj(t -> IndexedChar.of(t, idx.getAndIncrement())).iteratorEx(), true, INDEXED_CHAR_COMPARATOR);
    }

    @Override
    public Stream boxed() {
        assertNotClosed();

        return newStream(iteratorEx(), sorted, sorted ? CHAR_COMPARATOR : null);
    }

    @Override
    @SafeVarargs
    public final CharStream prepend(final char... a) {
        assertNotClosed();

        return prepend(CharStream.of(a));
    }

    @Override
    public CharStream prepend(CharStream stream) {
        assertNotClosed();

        if (isParallel()) {
            return CharStream.concat(stream, this).parallel(maxThreadNum(), splitor(), asyncExecutor(), cancelUncompletedThreads());
        } else {
            return CharStream.concat(stream, this);
        }
    }

    @Override
    public CharStream prepend(final OptionalChar op) {
        assertNotClosed();

        return prepend(op.stream());
    }

    @Override
    @SafeVarargs
    public final CharStream append(final char... a) {
        assertNotClosed();

        return append(CharStream.of(a));
    }

    @Override
    public CharStream append(CharStream stream) {
        assertNotClosed();

        if (isParallel()) {
            return CharStream.concat(this, stream).parallel(maxThreadNum(), splitor(), asyncExecutor(), cancelUncompletedThreads());
        } else {
            return CharStream.concat(this, stream);
        }
    }

    @Override
    public CharStream append(final OptionalChar op) {
        assertNotClosed();

        return prepend(op.stream());
    }

    @Override
    @SafeVarargs
    public final CharStream appendIfEmpty(final char... a) {
        assertNotClosed();

        return appendIfEmpty(() -> CharStream.of(a));
    }

    @Override
    public CharStream mergeWith(CharStream b, CharBiFunction nextSelector) {
        assertNotClosed();

        if (isParallel()) {
            return CharStream.merge(this, b, nextSelector).parallel(maxThreadNum(), splitor(), asyncExecutor(), cancelUncompletedThreads());
        } else {
            return CharStream.merge(this, b, nextSelector);
        }
    }

    @Override
    public CharStream zipWith(CharStream b, CharBinaryOperator zipFunction) {
        assertNotClosed();

        return CharStream.zip(this, b, zipFunction);
    }

    @Override
    public CharStream zipWith(CharStream b, CharStream c, CharTernaryOperator zipFunction) {
        assertNotClosed();

        return CharStream.zip(this, b, c, zipFunction);
    }

    //    @Override
    //    public CharStream cached() {
    //        return newStream(toArray(), sorted);
    //    }

    @Override
    public CharStream zipWith(CharStream b, char valueForNoneA, char valueForNoneB, CharBinaryOperator zipFunction) {
        assertNotClosed();

        return CharStream.zip(this, b, valueForNoneA, valueForNoneB, zipFunction);
    }

    @Override
    public CharStream zipWith(CharStream b, CharStream c, char valueForNoneA, char valueForNoneB, char valueForNoneC, CharTernaryOperator zipFunction) {
        assertNotClosed();

        return CharStream.zip(this, b, c, valueForNoneA, valueForNoneB, valueForNoneC, zipFunction);
    }

    @Override
    public  Map toMap(Throwables.CharFunction keyMapper,
            Throwables.CharFunction valueMapper) throws E, E2 {
        assertNotClosed();

        return toMap(keyMapper, valueMapper, Suppliers. ofMap());
    }

    @Override
    public , E extends Exception, E2 extends Exception> M toMap(Throwables.CharFunction keyMapper,
            Throwables.CharFunction valueMapper, Supplier mapFactory) throws E, E2 {
        assertNotClosed();

        return toMap(keyMapper, valueMapper, Fn. throwingMerger(), mapFactory);
    }

    @Override
    public  Map toMap(Throwables.CharFunction keyMapper,
            Throwables.CharFunction valueMapper, BinaryOperator mergeFunction) throws E, E2 {
        assertNotClosed();

        return toMap(keyMapper, valueMapper, mergeFunction, Suppliers. ofMap());
    }

    @Override
    public  Map groupTo(Throwables.CharFunction keyMapper, final Collector downstream)
            throws E {
        assertNotClosed();

        return groupTo(keyMapper, downstream, Suppliers. ofMap());
    }

    @Override
    public  void forEachIndexed(Throwables.IndexedCharConsumer action) throws E {
        assertNotClosed();

        if (isParallel()) {
            final AtomicInteger idx = new AtomicInteger(0);

            forEach(t -> action.accept(idx.getAndIncrement(), t));
        } else {
            final MutableInt idx = MutableInt.of(0);

            forEach(t -> action.accept(idx.getAndIncrement(), t));
        }
    }

    @Override
    public OptionalChar first() {
        assertNotClosed();

        try {
            final CharIterator iter = this.iteratorEx();

            return iter.hasNext() ? OptionalChar.of(iter.nextChar()) : OptionalChar.empty();
        } finally {
            close();
        }
    }

    @Override
    public OptionalChar last() {
        assertNotClosed();

        try {
            final CharIterator iter = this.iteratorEx();

            if (!iter.hasNext()) {
                return OptionalChar.empty();
            }

            char next = iter.nextChar();

            while (iter.hasNext()) {
                next = iter.nextChar();
            }

            return OptionalChar.of(next);
        } finally {
            close();
        }
    }

    @Override
    public OptionalChar onlyOne() throws DuplicatedResultException {
        assertNotClosed();

        try {
            final CharIterator iter = this.iteratorEx();

            final OptionalChar result = iter.hasNext() ? OptionalChar.of(iter.nextChar()) : OptionalChar.empty();

            if (result.isPresent() && iter.hasNext()) {
                throw new DuplicatedResultException("There are at least two elements: " + Strings.concat(result.get(), ", ", iter.nextChar()));
            }

            return result;
        } finally {
            close();
        }
    }

    @Override
    public  OptionalChar findAny(final Throwables.CharPredicate predicate) throws E {
        assertNotClosed();

        return findFirst(predicate);
    }

    @Override
    public  OptionalChar findFirstOrLast(Throwables.CharPredicate predicateForFirst,
            Throwables.CharPredicate predicateForLast) throws E, E2 {
        assertNotClosed();

        try {
            final CharIteratorEx iter = iteratorEx();
            MutableChar last = null;
            char next = 0;

            while (iter.hasNext()) {
                next = iter.nextChar();

                if (predicateForFirst.test(next)) {
                    return OptionalChar.of(next);
                } else if (predicateForLast.test(next)) {
                    if (last == null) {
                        last = MutableChar.of(next);
                    } else {
                        last.setValue(next);
                    }
                }
            }

            return last == null ? OptionalChar.empty() : OptionalChar.of(last.value());
        } finally {
            close();
        }
    }

    @Override
    public Optional> percentiles() {
        assertNotClosed();

        try {
            final char[] a = sorted().toArray();

            if (a.length == 0) {
                return Optional.empty();
            }

            return Optional.of(N.percentiles(a));
        } finally {
            close();
        }
    }

    @Override
    public Pair>> summarizeAndPercentiles() {
        assertNotClosed();

        try {
            final char[] a = sorted().toArray();

            if (N.isNullOrEmpty(a)) {
                return Pair.of(new CharSummaryStatistics(), Optional.> empty());
            } else {
                return Pair.of(new CharSummaryStatistics(a.length, sum(a), a[0], a[a.length - 1]), Optional.of(N.percentiles(a)));
            }
        } finally {
            close();
        }
    }

    @Override
    public String join(final CharSequence delimiter, final CharSequence prefix, final CharSequence suffix) {
        assertNotClosed();

        try {
            final Joiner joiner = Joiner.with(delimiter, prefix, suffix).reuseCachedBuffer();
            final CharIteratorEx iter = this.iteratorEx();

            while (iter.hasNext()) {
                joiner.append(iter.nextChar());
            }

            return joiner.toString();
        } finally {
            close();
        }
    }

    @Override
    public  R collect(Supplier supplier, ObjCharConsumer accumulator) {
        assertNotClosed();

        final BiConsumer combiner = collectingCombiner;

        return collect(supplier, accumulator, combiner);
    }
}