detect last foreach loop iteration

We Are Going To Discuss About detect last foreach loop iteration. So lets Start this Java Article.

detect last foreach loop iteration

Advertisements
  1. 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();

  2. 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();

Solution 1

Advertisements

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

Original Author Joao Pereira Of This Content

Solution 2

Advertisements

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

}

Original Author Edu G Of This Content

Solution 3

Advertisements

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.

Original Author Lazar Petrovic Of This Content

Solution 4

Advertisements

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

Original Author Manoj G Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment