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)
using iterator, No you dont have an option to get a previous key value. it has only hasNext() and next() methods.
Make your own Iterator:
public class EnhancedIterator<E> implements Iterator<E>{
private List<E> list;
private int indexSelected=-1;
public EnhancedIterator(List<E> list){
this.list=list;
}
@Override
public boolean hasNext() {
return indexSelected<list.size()-1;
}
@Override
public E next() {
indexSelected++;
return current();
}
@Override
public void remove() {
list.remove(indexSelected);
}
public void remove(int i){
list.remove(i);
if(i<indexSelected){
indexSelected--;
}
}
public E previous(){
indexSelected--;
return current();
}
public E current(){
return list.get(indexSelected);
}
public E get(int i){
return list.get(i);
}
}
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;
}
Ultimately Iterator
s are not fully suited for your task.
Why not create a List
from your Set
(via, eg, List list = new LinkedList(set)
) and iterate by using a standard indexed for-loop? That way you know the previous element is at i - 1
.