Reputation: 131288
I have the following construction: for (String playerName: players)
.
I would like to make a loop over all players
plus one more special player. But I do not want to modify the players
array by adding a new element to it. So, what can I do?
Can I replace players
in the for (String playerName: players)
by something containing all elements of the players
plus one more element?
Upvotes: 2
Views: 372
Reputation: 308269
I agree that @Bozhos answer is the best solution.
But if you absolutely want to use a single loop, you can use Iterables.concat()
from Google Collectons (together with Collections.singleton()
):
Iterable<String> allPlayersPlusOne=Iterables.concat(players,Collections.singleton(other));
for (String player : allPlayersPlusOne) {
//do stuff
}
Upvotes: 3
Reputation: 597412
Move the contents of the loop in another method, and call it both inside and outside:
for (String playerName : players) {
handlePlayer(playerName);
}
handlePlayer(anotherPlayerName);
Upvotes: 8