Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 615
mhery Avatar asked Jan 11 '17 12:01

mhery


People also ask

How do I find the last iteration of foreach?

Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.

How do you find the last value in a for loop?

You can use php end to get the last value of an array.

What is foreach loop with example?

C# provides an easy to use and more readable alternative to for loop, the foreach loop when working with arrays and collections to iterate through the items of arrays/collections. The foreach loop iterates through each item, hence called foreach loop.


Video Answer


2 Answers

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(", ")); 
like image 119
Joao Pereira Avatar answered Oct 10 '22 15:10

Joao Pereira


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  } 
like image 28
Edu G Avatar answered Oct 10 '22 15:10

Edu G