Replace for loop with for each and simplified logic.