I have an Iterator that I use on a HashMap, and I save and load the iterator. is there a way to get the previous key in the HashMap with Iterator? (java.util.Iterator)
I save it as an attribute in a Red5 connection and then load it back to continue working where i stopped.
I'm iterating through the keyset of the HashMap
Java ListIterator previous() MethodThe previous() method of ListIterator interface is used to return the previous element from the list and moves the cursor in a backward position. The above method can be used to iterate the list in a backward direction.
The next() method of ListIterator interface is used to return the next element in the given list. This method is used to iterate through the list.
hasPrevious. Returns true if this list iterator has more elements when traversing the list in the reverse direction. (In other words, returns true if previous() would return an element rather than throwing an exception.)
This has nothing to do with the position of the iterator. next() picks out and remembers the element at the pointer, then advances the pointer, then returns the remembered element. You're overthinking it. next() returns the next element in the sequence, starting with the first element.
You can use ListIterator
instead of Iterator
.
ListIterator has previous()
and hasPrevious()
methods.
Not directly, as others pointed out, but if you e.g. need to access one previous element you could easily save that in a separate variable.
T previous = null;
for (Iterator<T> i = map.keySet().iterator(); i.hasNext();) {
T element = i.next();
// Do something with "element" and "previous" (if not null)
previous = element;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With