Jeff Jeff - 4 months ago 29
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(! {
for(int i = 0; i < this.table.GetPlayerCount() && !; i++) {
DealOneCardToPlayer(this.table.players.get(i) ,;;

I suspect that there is a way to use something like this: { do suff }

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


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

IntStream.range(0, -> {
        this.table.players.get(idx % this.table.GetPlayerCount()),;

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

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 =, numCardsToDeal);
IntStream.range(0, cardsToDeal.size()).forEach(idx -> {
        this.table.players.get(idx % this.table.GetPlayerCount()),