Spliterator issue?

Ben Evans benjamin.john.evans at gmail.com
Sat Mar 23 08:25:08 PDT 2013


Hi,

I've rewritten the MatcherIterator for the Pattern point
lambdafication to properly cache values and have an idempotent
hasNext(), like this:

    private static class MatcherIterator implements Iterator<CharSequence> {
	private final Matcher curMatcher;
        private final CharSequence input;
	private int current = 0;
        private CharSequence nextElement = null;
	private boolean valueReady = false;

	MatcherIterator(CharSequence in, Matcher m) {
	    input = in;
	    curMatcher = m;
	}

	public void accept(CharSequence t) {
	    valueReady = true;
	    nextElement = t;
	}
	
	public CharSequence next() {
	    if (!valueReady && !hasNext())
		throw new NoSuchElementException();
	    else {
		valueReady = false;
		return nextElement;
	    }
	}

	public boolean hasNext() {
	    if (!valueReady) {
		if (current == input.length()) return false;
		if (curMatcher.find()) {
		    nextElement = input.subSequence(current, curMatcher.start());
		    current = curMatcher.end();
		    valueReady = true;
		} else {
		    nextElement = input.subSequence(current, input.length());
		    current = input.length();
		    valueReady = true;
		}
	    }
	    return true;
	}
    }

    public Stream<CharSequence> splitAsStream(final CharSequence input) {
	return Streams.stream(Spliterators.spliteratorUnknownSize(new
MatcherIterator(input, p.matcher(input)), Spliterator.ORDERED));
    }

which seems to behave the way that I expect, except that calling
splitAsStream() causes a NoSuchElementException to always be thrown.

Has something changed in the implementation of Spliterator which
causes this to happen?

Thanks,

Ben


More information about the lambda-dev mailing list