user3001764
user3001764

Reputation: 31

iterator, do something when hasNext() equals false

I have a while loop that iterates through an ArrayList but I want to do something when the iteration reaches the last string in this list of strings.

How could this be done?

Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {

            //do stuff here
            }

            do something to list string in list?

Upvotes: 1

Views: 1713

Answers (5)

BilalDja
BilalDja

Reputation: 1092

try this code :

ArrayList<String> list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
        list.add("Fore");
        list.add("Last");

        Iterator<String> iterator = list.iterator();

        while(iterator.hasNext()) {
            String item = iterator.next();
            i++;
            if(!iterator.hasNext()) {
                // do what you want with the last one
                System.out.println(item);
            }
        }

Hope that helps, Salam

Upvotes: 0

user1983983
user1983983

Reputation: 4841

You could do it that way if you would like to do it inside the loop and to prevent a NullPointerException when the list is empty:

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    //do something here
    if(!iterator.hasNext()) {
        //do stuff with last item here
    }
}

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

try something like this:

string lastItem = list.get(list.size() - 1);

update

as per your comment you need to user iterator.hasNext() so you can try(which is not recommended):

for(int i=0;i<list.size();i++) 
{
   if(!iterator.hasNext())
   {
     //do stuff here
   }
}

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200158

Have a local variable in the outer scope to remember the last item:

String last = null;
while (iterator.hasNext()) {
  last = iterator.next();
}

... now last refers to the last item.

If you want to know you're on the last item while still within the loop, then simply check that with hasNext() after having called next() to retrieve the current iteration's item.

while (iterator.hasNext()) {
  String s = iterator.next();
  if (!iterator.hasNext()) {
     // here s is guaranteed to refer to the last item
  }
}

Upvotes: 2

Trying
Trying

Reputation: 14278

String str = null;
while (iterator.hasNext()) {
  str = iterator.next();//str will contain the string
}
System.out.print(str);

or

arrayList.get(arrayList.size()-1);

Upvotes: 1

Related Questions