Is there a Guava Iterator (or methodology) for List objects which allows two iterator instances to exist – in the same memory scope – while allowing the remove() operation? (Bonus point: if it works for a Collection).
Example use case: an outer and an inner iteration through a collection, where the inner loop might decide to remove an element and the outer loop would subsequently skip it.
Imagine how it would benefit the following concept code (which uses Guava static imports) by reducing the number of elements to compare in the loop and also removing the need to remove empty sets from the list at the end:
private <T> Set<Set<T>> disjointify(Collection<Set<T>> sets) {
List<Set<T>> disjoint = newArrayList(sets);
for (Set<T> set1 : disjoint) {
for (Set<T> set2 : filter(disjoint, not(equalTo(set1)))) {
if (!intersection(set1, set2).isEmpty()) {
// this wouldn't be safe for a Set<Set<T>>
set1.addAll(set2);
set2.clear();
}
}
}
return newHashSet(filter(disjoint, NO_EMPTIES));
}
private static final Predicate<Set<?>> NO_EMPTIES = new Predicate<Set<?>>() {
@Override
public boolean apply(Set<?> input) {
if (input == null || input.isEmpty()) {
return false;
}
return true;
}
};
Note: one can easily imagine creating the implementation – especially for LinkedList – I’m just asking if one already exists here.
For the record, if an efficient Iterable did already exist, and worked for Sets, then the use case would look like the following (I have created my own very inefficient Iterable which achieves this, but it is 50 lines long and ludicrously inefficient – so I use the original code above):
private <T> void disjointify(Set<Set<T>> sets) {
for (Set<T> set1 : nestable(sets)) {
Iterator<Set<T>> it = filter(nestable(sets), not(equalTo(set1))).iterator();
while (it.hasNext()) {
Set<T> set2 = it.next();
if (!intersection(set1, set2).isEmpty()) {
set1.addAll(set2);
it.remove();
}
}
}
}
It would appear that such an implementation does not exist in standard libraries.