In many algorithms, you have to iterate over a set of elements, and the set is not empty.
Since you can change a set during iteration, you usually pull an element out of the set and then iterate, possibly adding or removing elements from or from the set. Here is a typical Java code for this.
Set<Integer> possibleFactors = Sets.newHashSet(2,3,4,5,6,7,8,100); while (!possibleFactors.isEmpty()) { int factor = possibleFactors.iterator().next(); for (int i=1;i<10;i++) possibleFactors.remove(i*factor); }
edit: As stated in the comments, I will give a better example. I repeat the files selected by the user and I filter them by checking the permissions of each element. However, as an optimization, if the user does not have permission for a specific directory, I will remove all files from it from the set.
Set<Path> input = Sets.newHashSet(userSelectedPaths); while (!input.isEmpty()) { Path path = input.iterator.next(); input.remove(path); if (!expensivePermissionCheck(path)) { input.removeAll(path.getFiles()); } else { processPath(path); } }
However, the first line in the loop looks strange. It creates superfluous Iterable objects, when all I want is an arbitrary element from the set, it doesn't matter to me in which order.
Besides performance, it looks weird and less readable.
Is there a better alternative? Maybe a completely different structure?
edit: Perhaps the best wording would be, "How do I place an arbitrary element from a set?"
Elazar leibovich
source share