Reputation: 5435
Take a situation where you have, let's say, an ArrayList that supports a remove function -- it deletes the entry and shifts everything to the right of it left one.
If I want to remove things from the list under a certain condition, I might do this:
for (int i = 0; i < list.size(); i++) {
if (condition) {
list.remove(i);
i--;
}
}
but this is ugly and feels hackish. You could do the same with an Iterator, but you shouldn't be altering lists while using iterators.
So what's the non-ugly solution?
Upvotes: 0
Views: 410
Reputation: 2717
Guava provides some functional flavour to Java. In your case it would be:
FluentIterable.from(your_iterable).filter(new Predicate<Type_contained_in_your_iterable>() {
@Override
public boolean apply(@Nullable Type_contained_in_your_iterable input) {
return {condition};
}
});
Note that your predicate will only return the elements from your iterable satisfying your condition. Much clearer like this. Isn't it.
Upvotes: 0
Reputation: 18492
Iterators can in fact be used for that purpose, and is what the Oracle documentation recommends.
This is code provided by the above link under Traversing Collections - Iterators:
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
Most importantly, above that example they state:
Note that
Iterator.remove
is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
Upvotes: 2
Reputation: 840
Try this
Iterator itr = list.iterator();
while(itr.hasNext()) {
if(condition)
itr.remove();
}
Hope so this shud work.. try else ll suggest another one
I have another one for you which checks for condition too....
int count=0;
Iterator itr = list.iterator();
while(itr.next()) {
count++;
if(condition=count)
itr.remove();
}
Upvotes: 0
Reputation: 5786
I just use a loop, but decrement the counter instead
for(int i=list.size()-1; i>=0; --i) {
if(condition) {
list.remove(i);
}
}
Upvotes: 1