Lukasz Medza
Lukasz Medza

Reputation: 499

Access previous element with iterator

The idea is that I have a list of words and the user searches for a word on the list and then depending on what the word is you either print off the following or the preceding word. It was simple enough to do it with the following word like so :

public void pirateToEnglish(){
        System.out.println("Enter the word that you want to translate ");
        String nameSearch;
        nameSearch=input.nextLine();

        Iterator<Phrase> it = phrases.iterator();
        while(it.hasNext())
        {
            Phrase c = it.next();
            if (c.getName().equals(nameSearch))  {
                System.out.println( it.next().toString());      
                return;
            }
        }

        System.out.println("not on list");
    }

But I'm struggling to do this with the preceding word because the iterator has no previous method. Any ideas on how to get this to work would be very appreciated

Upvotes: 0

Views: 1045

Answers (4)

Nils
Nils

Reputation: 806

You can store previous element in a string like this:

 String previous = "";
 while(it.hasNext())
    {
        Phrase c = it.next();
        if (c.getName().equals(nameSearch))  {
            System.out.println( "Previous : " + previous); 
            System.out.println( "Next : " + it.next().toString());      
            return;
        }
        previous = c.getName(); //Convert current element to String or c.getName() whichever is applicable.
    }

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

try ListIterator instead of Iterator. ListIterator has previous() method to access the previous element in the list.

ListIterator<Phrase> iterator = phrases.listIterator();
Phrase p = iterator.previous();

Upvotes: 3

BobTheBuilder
BobTheBuilder

Reputation: 19284

You can either use ListIterator or save the previous item in a variable inside your loop.

Another issue - calling it.next() twice is unsafe as you only check it.hasNext() once.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691655

Use a ListIterator. A ListIterator is able to iterate in both directions.

Upvotes: 1

Related Questions