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.
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.
You can use php end to get the last value of an array.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With