Replace complex for loop for foreach, count and break

Change-Id: If1d3193f9579ce6b0d3c790b234d56ea1fe73237