Catfish
Catfish

Reputation: 19294

Is it possible to get the index of a for-each loop in Java

Given the code below, is it possible to remove the index of p from the properties list using this style of for loop in Java?

List<Properties> propertiesList = new ArrayList<Properties>();
String keyToDelete = "blah";

for(Properties p : propertiesList) {
    if(p.getKey().equals(keyToDelete)) {
        propertiesList.remove(index) //How to remove the element at index 'p'
    }
}

This is how i would accomplish this with the other for loop

List<Properties> propertiesList = new ArrayList<Properties>();
String keyToDelete = "blah";

for(int i = 0; i < propertiesList.size(); i++) {
        if(p.getKey().equals(keyToDelete)) {
                propertiesList.remove(i);
        }
}

Upvotes: 17

Views: 6609

Answers (5)

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

How about using proper Iterator and its remove method?

List<Properties> propertiesList = new ArrayList<Properties>();
String keyToDelete = "blah";

for (
    Iterator<Properties> iter = propertiesList.iterator( );
    iter.hasNext( );
)
{
    Properties p = iter.next( );

    if(p.getKey().equals(keyToDelete)) {
        iter.remove( );
    }
}

Upvotes: 8

Tom Anderson
Tom Anderson

Reputation: 47193

The way to do this is with an explicit Iterator (no school like the old school!).

Iterator<Properties> it = propertiesList.iterator();
while (it.hasNext()) {
    if (it.next().getKey().equals(keyToDelete)) {
        it.remove();
    }
}

Unlike the remove method on a list, the remove method on the iterator doesn't cause a concurrent modification. It's the only safe way to remove an element from a collection you're iterating over. As the javadoc for that method says:

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Upvotes: 27

F.X
F.X

Reputation: 87

As Tim Anderson suggested you could also modify the list outside the loop

List<Properties> propertiesList = new ArrayList<Properties>();
String keyToDelete = "blah";
List<Properties> propertiesToRemove = new ArrayList<Properties>();


for(Properties p : propertiesList) {
    if(p.getKey().equals(keyToDelete)) {
        propertiesToRemove.add(p) ;
    }
}

propertiesList.removeAll(propertiesToRemove);

Upvotes: 2

Vladmir
Vladmir

Reputation: 1265

As far as I know, foreach loop does not guarantee the order of elements it enumerates,

so if you will try Collection[i] you can get another element rather than currently iterated

It is can be clearly viewed in some multithreaded cases

Upvotes: 1

Keppil
Keppil

Reputation: 46219

No, you need to use the old-school for loop to get an index.

You could of course add it yourself to the for-each loop, but then you would most probably be better off using the old variant instead.

Upvotes: 8

Related Questions