How do I "peek" the next element on a Java Scanner?

Here is another wrapper based solution, but this one has only one internal scanner. I left the other up to show one solution, this is a different, and probably better solution. Again, this solution doesn't implement everything (and is untested), but you will only have to implement those parts that you intend to use.

In this version you would keep around a reference to what the next() actually is.

import java.util.Scanner;

public class PeekableScanner
{
    private Scanner scan;
    private String next;

    public PeekableScanner( String source )
    {
        scan = new Scanner( source );
        next = (scan.hasNext() ? scan.next() : null);
    }

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

    public String next()
    {
        String current = next;
        next = (scan.hasNext() ? scan.next() : null);
        return current;
    }

    public String peek()
    {
        return next;
    }
}

There is a PeekingIterator that's documented in Google Guava.


I don't think there is a peek-like method, but you can use hasNext(String) to check if the next token is what you are looking for.

Tags:

Java

Iterator