Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate and modify Java Sets?

Tags:

java

set

Let's say I have a Set of Integers, and I want to increment every Integer in the Set. How would I do this?

Am I allowed to add and remove elements from the set while iterating it?

Would I need to create a new set that I would "copy and modify" the elements into, while I'm iterating the original set?

EDIT: What if the elements of the set are immutable?

like image 550
Buttons840 Avatar asked Sep 12 '11 20:09

Buttons840


People also ask

Can you modify a set Java?

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

How will you iterate set in Java?

Example 2: Iterate through Set using iterator() We have used the iterator() method to iterate over the set. Here, hasNext() - returns true if there is next element in the set. next() - returns the next element of the set.

Can we modify list while iterating Java?

Even though java. util. ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.

Can we modify collection while iterating?

It is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances.


1 Answers

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers ... Set<Integer> temp = new Set<Integer>(); for(Integer i : s)     temp.add(i+1); s.clear(); s.addAll(temp); 
like image 136
Jonathan Weatherhead Avatar answered Sep 18 '22 06:09

Jonathan Weatherhead