Home Ask Login Register

Developers Planet

Your answer is one click away!

PT_C February 2016

Foreach not hitting last item

I have a foreach that is suppose to go through and arraylist and perform an action every time an item changes.

So it for something like:

ID | Request
1  |   z
2  |   e

it sends an email to 1 saying "You have 1 request". Then an email to 2 "You have 1 request" and so on.

My loop doesn't address the last item when there's only 2 items in the list and I'm having a difficult time trying to figure out the elegant way to address it.

Integer managerId = null;
Integer previousManagerId = null;
if(requests != null && requests.size() > 0){
        for(Request request : requests){
            managerId = request.getId();

            if((!managerId.equals(previousId) && previousId != null)){
                e.sendEmail(previousId, numReq.toString());
                numReq = 0;
            }
            numReq++;

            previousId = managerId;

        }
        //Suppose to address the last item. Fails when size == 2
        if((!managerId.equals(previousId) && previousId != null)){
            eusendEmail(previousId, numReq.toString());
        }

Answers


TimK February 2016

The last statement of the loop ensures that previousId is always equal to managerId after the loop ends, so it can never go into the if.

I think you always want to send the last email because you know there was at least one request.


J. Doe February 2016

You have to save the previousId outside the for each because it will delet this value every time it goes trough the next object ;)

But why are you doing the first if? Wouldn't the foreach do that anyway?

How if you try like this:

    String managerId = "";
    for(Request request : requests){
        managerId = request.getId();

        if(!managerId.equals(previousId)){
            request.sendEmail(previousId, numReq.toString());
            numReq = 0;
        }
        numReq++;
    }

Post Status

Asked in February 2016
Viewed 2,542 times
Voted 8
Answered 2 times

Search




Leave an answer


Quote of the day: live life