0

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?

Jeremy
  • 5,365
  • 14
  • 51
  • 80
  • possible duplicate of [Deleting objects from an ArrayList in Java](http://stackoverflow.com/questions/1310532/deleting-objects-from-an-arraylist-in-java) – Brian Roach Nov 03 '11 at 04:05

4 Answers4

2

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.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
1

I just use a loop, but decrement the counter instead

for(int i=list.size()-1; i>=0; --i) {
  if(condition) {
     list.remove(i);
  }
}
aleph_null
  • 5,766
  • 2
  • 24
  • 39
0

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.

chaiyachaiya
  • 2,617
  • 18
  • 19
0

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();
} 
shanmugamgsn
  • 820
  • 5
  • 16
  • 27