mhery
mhery

Reputation: 2248

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.

Upvotes: 79

Views: 150657

Answers (10)

Joao Pereira
Joao Pereira

Reputation: 2534

For simplicity and understandability I would do this:

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

Upvotes: 85

Chhorn Elit
Chhorn Elit

Reputation: 5588

    List<String> list = Arrays.asList("1", "2", "3");
    for (String each : list) {
        if (list.indexOf(each) == (list.size() - 1)) {
            System.out.println("last loop");
        }
    }

Note: Set is NOT an ordered collection.

Upvotes: 0

gotwo
gotwo

Reputation: 870

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.

Upvotes: 4

Mohamed Zaki
Mohamed Zaki

Reputation: 47

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.

Upvotes: 0

Manoj G
Manoj G

Reputation: 63

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

Upvotes: 4

luk4
luk4

Reputation: 7

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

Upvotes: 0

Edu G
Edu G

Reputation: 1070

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

}

Upvotes: 45

CraigR8806
CraigR8806

Reputation: 1584

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.

Upvotes: 0

Lazar Petrovic
Lazar Petrovic

Reputation: 537

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.

Upvotes: 28

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

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.

Upvotes: 0

Related Questions