How to remove an element from set using Iterator?
Posted
by
ankit
on Stack Overflow
See other posts from Stack Overflow
or by ankit
Published on 2014-08-21T10:04:29Z
Indexed on
2014/08/21
10:20 UTC
Read the original article
Hit count: 174
I have a scenario that I am iterating over a set using iterator. Now I want to remove 1st element while my iterator is on 2nd element. How can I do it.
I dont want to convert this set to list and using listIterator.
I dont want to collect all objects to be removed in other set and call remove all
sample code.
Set<MyObject> mySet = new HashSet<MyObject>();
mySet.add(MyObject1);
mySet.add(MyObject2);
...
Iterator itr = mySet.iterator();
while(itr.hasNext())
{
// Now iterator is at second element and I want to remove first element
}
© Stack Overflow or respective owner