Search code examples
javaiterator

how to leave Iterator by the same object?


If I create a new object the program is working properly:

Iterator iter = Students.iterator();
    while (iter.hasNext()){
        Student newstudent=(Student) iter.next();
        if (newstudent.getCourse()==2){
            System.out.println(  newstudent.getName());}

But if do not like to:

Iterator iter = Students.iterator();
  while (iter.hasNext()){
   if (((Student) iter.next()).getCourse()==2){
     System.out.println(( (Student)iter.next()).getName());}//Here it is printing out the next object afther that I have checked

How to stay by the same object?


Solution

  • If you don't want to advance the iterator you could always consider using a PeekingIterator, which allows you to peek at the next element without removing it, e.g.:

    final Iterator<Student> iter = Iterators.peekingIterator(Students.iterator());
    
    final Student a = iter.peek();
    final Student b = iter.peek();
    final Student c = iter.next();
    
    assert a == b == c;
    

    The PeekingIterator is included in Google's Guava library, although it would be easy to roll your own.