Jeff Jeff - 1 month ago 13
Java Question

use List Foreach instead of for() Java

I'm currently learning Java and I'm interested in learning how to use the list foreach method rather than using a manually constructed for loop. I suspect they can perform the same.

My current code looks like this:

while(!this.cards.isEmpty()) {
for(int i = 0; i < this.table.GetPlayerCount() && !this.cards.isEmpty(); i++) {
DealOneCardToPlayer(this.table.players.get(i) ,this.cards.get(0));
this.cards.remove(0);
}
}


I suspect that there is a way to use something like this:

this.cards.foreach() { do suff }


but I haven't quite been able to nail down the syntax... can someone give me a quick hand?

Answer

I think you can do it by iterating over the indexes of the cards:

IntStream.range(0, this.cards.size()).forEach(idx -> {
    DealOneCardToPlayer(
        this.table.players.get(idx % this.table.GetPlayerCount()),
        this.cards.get(idx));
});

Although this doesn't remove the cards as you go; if you really need this.cards to be empty after:

this.cards.clear();

If you want to limit the number of cards dealt out (e.g. you want to deal N cards to each player), the easiest way is to extract a sublist, and then just apply the same method above:

List<Card> cardsToDeal = this.cards.subList(0, numCardsToDeal);
IntStream.range(0, cardsToDeal.size()).forEach(idx -> {
    DealOneCardToPlayer(
        this.table.players.get(idx % this.table.GetPlayerCount()),
        cardsToDeal.get(idx));
});
cardsToDeal.clear();
Comments