Previous entry iterator – Java [copy]

See English answer > iterator has next() – is there a way to get the previous element instead of the next one? 10

Iterator iterator= hm.entrySet().iterator();
    Map.Entry entry = (Map.Entry) iterator.next();

Now I'm creating a virtual iterator to point to the previous entry Is there any other way to do this?

Solution

I don't know, but you can store it in a local variable so that you can access it in each 'next' iteration-

Iterator iterator = hm.entrySet().iterator();
Object prev = null;

while (iterator.hasNext()) {
    Object next = iterator.next();
    // Do your stuff
    prev = next;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>