detect last foreach loop iteration

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.


If you are working with a complex object and not just a plain list/set the below code might help. Just adding a map function to actually get the desired string before you collect.

String result = violations.stream().map(e->e.getMessage()).collect(Collectors.joining(", "));

For simplicity and understandability, imo, would do:

Set<String> names = new HashSet<>();
Iterator<String> iterator = names.iterator();
    while (iterator.hasNext()) {
        String name = iterator.next();
        //Do stuff
        if (!iterator.hasNext()) {
            //last name 
        }
     }

Also, it depends on what you're trying to achieve. Let's say you are implementing the common use case of separating each name by coma, but not add an empty coma at the end:

Set<String> names = new HashSet<>();
names.add("Joao");
names.add("Pereira");

//if the result should be Joao, Pereira then something like this may work
String result = names.stream().collect(Collectors.joining(", "));

Other answears are completely adequate, just adding this solution for the given question.

Set<String> names = new HashSet<>();

   //some code
   int i = 0;

for (String name: names) {
    if(i++ == names.size() - 1){
        // Last iteration
    }
   //some code

}