Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);
        }
}
like image 707
Catfish Avatar asked Jul 19 '12 15:07

Catfish


People also ask

Does foreach have an index?

C#'s foreach loop makes it easy to process a collection: there's no index variable, condition, or code to update the loop variable. Instead the loop variable is automatically set to the value of each element. That also means that there's no index variable with foreach .

What is the index in a for loop?

The index value represents the number of the currently executing iteration. More specifically, the body of the loop (the instructions that are executed during each loop repetition) can be said to be iterated as the loop executes.

Can we use for-each loop for list in Java?

Each element in the list can be accessed using iterator with a while loop.


2 Answers

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.

like image 161
Tom Anderson Avatar answered Oct 06 '22 15:10

Tom Anderson


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.

like image 40
Keppil Avatar answered Oct 06 '22 15:10

Keppil