detect last foreach loop iteration

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(", "));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)