Skip to content
Advertisement

detect last foreach loop iteration

Supposing that I have some foreach loop like this:

Set<String> names = new HashSet<>();
//some code
for (String name: names) {
     //some code
}

Is there a way to check inside foreach that the actual name is the last one in Set without a counter? I didn’t found here some question like this.

Advertisement

Answer

There isn’t, take a look at How does the Java ‘for each’ loop work?

You must change your loop to use an iterator explicitly or an int counter.

Advertisement