17

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.

6 Answers 6

18

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;
    }
}
11

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.

8

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

2
  • 3
    Guava's PeekingIterator is the most elegant solution here -- it is fast, well-tested and it is essentially a single-line solution to OP's problem.
    – Augustin
    Mar 30, 2016 at 16:55
  • Agree. Or Apache Commons implementation. Jun 29, 2020 at 20:19
6

Here's a much simpler answer to all the others.

We can use the match() method to retrieve the last match of hasNext, and look at the 0th capture group (which is the entire string matched by the regex --- exactly what we want).

Scanner s = ​new Scanner("a\nb")​​​​​​;

s.hasNext(".*"); // ".*" matches anything, similar to hasNext(), but updates the scanner's internal match variable
s.match().group(0)​;​ // returns "a"

s.next() // returns "a"
4

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;
    }
}
4
  • It occurs to me that you could probably do it in one scanner just keeping the reference to the next() object. Nov 26, 2010 at 22:03
  • Ok, I added that answer as another answer (I didn't want to simply add it to this one because I wanted to keep this up as one possible solution). In some cases (if you are doing fairly complex things with your scanners) this might be easier to wrap, but the other solution is more efficient. Nov 26, 2010 at 22:11
  • Note that your PeekableScanner constructor would throw NoSuchElementException if the string were empty or contained only whitespace. Jul 2, 2014 at 21:24
  • I ended up requiring this, due to having to use next(RegEx). With the other solution, you'd have the "next" from the last call, and you'd queue the regexed next for the next next. (at least with a "straightforward" implementation, but then it's better to just grab this than try to fix the other).
    – efaj
    Mar 10, 2016 at 9:20
1

If the Iterator is a ListIterator you can do something like this:

if(it.hasNext()) {
   if(it.next() ... 
   it.previous();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.