Juan Pablo Santos Juan Pablo Santos - 9 months ago 19
Java Question

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

That is, how do I get the next element of the iterator without removing it? As I may or may not want to remove it depending on its content. I have a file scanner where I iterate over XML tags using the Scanner next() method.

Thanks in advance.


See this answer for a more efficient solution.

This is a very ugly solution, but you can create a wrapper class around Scanner which keeps two internal Scanner objects. You can get peek() functionality by having the second scanner one ahead of the other

This is a very basic solution (just to give you an idea of what I'm talking about) and doesn't implement all that you would need (but you would only need to implement those parts you would use). (also, this is untested, so take it with a grain of salt).

import java.util.Scanner;

public class PeekableScanner
    private Scanner scan1;
    private Scanner scan2;
    private String next;

    public PeekableScanner( String source )
        scan1 = new Scanner(source);
        scan2 = new Scanner(source);
        next = scan2.next();

    public boolean hasNext()
        return scan1.hasNext();

    public String next()
        next = (scan2.hasNext() ? scan2.next() : null);
        return scan1.next();

    public String peek()
        return next;