Created
October 5, 2017 19:23
-
-
Save rokon12/efe1693f0ef9b355695e2a4c7fa12450 to your computer and use it in GitHub Desktop.
Demo of cartesian product
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.bazlur; | |
import java.util.EnumSet; | |
import java.util.Set; | |
import java.util.List; | |
import java.util.function.BiFunction; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class Card { | |
enum Suit { | |
CLUBS, | |
SPADES, | |
HEARTS, | |
DIAMONDS | |
} | |
enum RANK { | |
ACE, | |
TWO, | |
THREE, | |
FOUR, | |
FIVE, | |
SIX, | |
SEVEN, | |
EIGHT, | |
NIGHT, | |
TEN, | |
JACK, | |
QUEEN, | |
KING | |
} | |
private Suit suit; | |
private RANK rank; | |
public Card(Suit suit, RANK rank) { | |
this.suit = suit; | |
this.rank = rank; | |
} | |
@Override | |
public String toString() { | |
return suit + " - " + rank; | |
} | |
private static <A, B, C> Stream<C> cartesianProduct(Set<A> setA, Set<B> setB, | |
BiFunction<A, B, C> function) { | |
return setA.stream() | |
.flatMap(first -> | |
setB.stream() | |
.map(second -> function.apply(first, second))); | |
} | |
public static List<Card> allCards() { | |
return cartesianProduct( | |
EnumSet.allOf(Suit.class), | |
EnumSet.allOf(RANK.class), | |
Card::new) | |
.collect(Collectors.toList()); | |
} | |
public static void main(String[] args) { | |
Card.allCards() | |
.forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment