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

org.davidmoten.kool.internal.operators.stream.Split Maven / Gradle / Ivy

There is a newer version: 0.1.35
Show newest version
package org.davidmoten.kool.internal.operators.stream;

import java.util.NoSuchElementException;

import org.davidmoten.kool.Stream;
import org.davidmoten.kool.StreamIterator;

public final class Split implements Stream {

    private final String delimiter;
    private final Stream source;

    public Split(String delimiter, Stream source) {
        this.delimiter = delimiter;
        this.source = source;
    }

    @Override
    public StreamIterator iterator() {
        return new StreamIterator() {

            StreamIterator it = source.iteratorNullChecked();
            StringBuilder b = new StringBuilder();
            String next;
            int startFrom;

            @Override
            public boolean hasNext() {
                loadNext();
                return next != null;
            }

            @Override
            public String next() {
                loadNext();
                if (next == null) {
                    throw new NoSuchElementException();
                } else {
                    String t = next;
                    next = null;
                    return t;
                }
            }

            @Override
            public void dispose() {
                it.dispose();
            }

            private void loadNext() {
                if (b != null && next == null) {
                    if (startFrom <= b.length() - delimiter.length()) {
                        int i = b.indexOf(delimiter, startFrom);
                        if (i != -1) {
                            next = b.substring(0, i);
                            b.delete(0, i + delimiter.length());
                            startFrom -= i + delimiter.length();
                            return;
                        }
                    }
                    while (it.hasNext()) {
                        String s = it.nextNullChecked().toString();
                        b.append(s);
                        int i = b.indexOf(delimiter, startFrom);
                        if (i != -1) {
                            next = b.substring(0, i);
                            b.delete(0, i + delimiter.length());
                            startFrom -= i + delimiter.length();
                            return;
                        }
                    }
                    if (b.length() > 0) {
                        next = b.toString();
                    } 
                    b = null;
                }
            }
        };
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy