Converting classic nested for loops using java 8 streams

See English answers > Cartesian product of streams in Java 8 as streams (using streams only)

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

I'm out

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 side effects in the list

Is there another elegant way to generate lists from streams instead of?

Solution

use

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

In fact, it is a simple Cartesian product I started with Cartesian product of streams in Java 8 as stream (using streams only) and adapted to your situation If you want to do the third loop in it, you need to use the code in this answer

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>