detect last foreach loop iteration

JavaAlgorithmCollections

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

}

Solution 3 - Java

There isn't, take a look at https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work

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

Solution 4 - Java

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

Solution 5 - Java

Yes, there is a way to check it inside of foreach, by use of a counter:

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

int i = names.size() - 1;
for (String name: names) {
    if (i-- == 0) {
        // some code for last name
    }
    //some code
}

Consider, names.size() is called only one time outside of the loop. This makes the loop faster than processing it multiple times within the loop.

Solution 6 - Java

There is no build in method to check if the current element is also the last element. Besides that you are using a HashSet which does not guarantee the return order. Even if you want to check it e.g. with an index i the last element could always be a different one.

Solution 7 - Java

A Set does not guaranty order over of items within it. You may loop through the Set once and retrieve "abc" as the "last item" and the next time you may find that "hij" is the "last item" in the Set.

That being said, if you are not concerned about order and you just want to know what the arbitrary "last item" is when observing the Set at that current moment, there is not built in way to do this. You would have to make use of a counter.

Solution 8 - Java

.map(String::toString) from the answer above is redundant, because HashSet already contains String values. Do not use Set to concatenate strings because the order is not assured.

List<String> nameList = Arrays.asList("Michael", "Kate", "Tom");
String result = nameList.stream().collect(Collectors.joining(", "));

Solution 9 - Java

There is an easy way you can do this throw one condition. consider this is your array:

int odd[] = {1,3,5,7,9,11};

and you want to print it all in one line with " - " hyphen between them except the last one.

for(int aa:odd) {
    System.out.print(aa);
 			
    if(odd[odd.length - 1] != aa)
        System.out.print(" - ");
}

this condition

if( odd[odd.length - 1] != aa )

will check if you aren't in the last element so you can still add " - ", otherwise you will not add it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmheryView Question on Stackoverflow
Solution 1 - JavaJoao PereiraView Answer on Stackoverflow
Solution 2 - JavaEdu GView Answer on Stackoverflow
Solution 3 - JavaLazar PetrovicView Answer on Stackoverflow
Solution 4 - JavaManoj GView Answer on Stackoverflow
Solution 5 - JavagotwoView Answer on Stackoverflow
Solution 6 - JavaMurat KaragözView Answer on Stackoverflow
Solution 7 - JavaCraigR8806View Answer on Stackoverflow
Solution 8 - Javaluk4View Answer on Stackoverflow
Solution 9 - JavaMohamed ZakiView Answer on Stackoverflow