Convert classic nested loops with Java 8 threads

I want to convert the following code using the Java 8 thread API

List<Card> deck = new ArrayList<>();
for (Suit s: Suit.values())
{
    for (Rank r: Rank.values())
    {
        deck .add(new Card(r, s));
    }
}

I went out with this

List<Card> deck = new ArrayList<>();
Arrays.stream(Suit.values())
    .forEach(s -> Arrays.stream(Rank.values())
        .forEach(r -> deck.add(new Card(r, s))));

but I don’t like it because it has a side effect on the list.

Is there another elegant way that creates a list from a stream, maybe?

+4
source share
1 answer

Use

List<Card> cards = Arrays.stream(Suit.values())
                .flatMap(s -> Arrays.stream(Rank.values()).map(r -> new Card(r, s)))
                .collect(Collectors.toList());

This is actually just a Cartesian product. I gave an example from the Cartesian product of threads in Java 8 as a stream (using only streams) and adapted to your case. If you want to make a third loop inside, you need to use the code from this answer.

+5

Source: https://habr.com/ru/post/1666797/


All Articles