-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlatMapMain.java
More file actions
97 lines (82 loc) · 2.27 KB
/
FlatMapMain.java
File metadata and controls
97 lines (82 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package chapter7.lambdas;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* 使用flatMap
*/
public class FlatMapMain {
public static void main(String[] args) {
System.out.println(newDeckByIterative());
System.out.println(newDeckByStream());
}
/**
* 迭代方法计算笛卡尔积,即生成一副扑克
*/
static List<Card> newDeckByIterative(){
List<Card> result = new ArrayList<>();
for (Suit suit : Suit.values()) {
for (Rank rank : Rank.values()) {
result.add(new Card(suit, rank));
}
}
return result;
}
/**
* 流式计算笛卡尔积,即生成一副扑克
*/
static List<Card> newDeckByStream(){
return Arrays.stream(Suit.values()).flatMap(suit ->
Arrays.stream(Rank.values()).map(rank -> new Card(suit, rank))
).collect(Collectors.toList());
}
static final class Card{
private final Suit suit;
private final Rank rank;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Card card = (Card) o;
return suit == card.suit && Objects.equals(rank, card.rank);
}
@Override
public int hashCode() {
return Objects.hash(suit, rank);
}
@Override
public String toString() {
return suit.symbol + rank.symbol;
}
public Card(Suit suit, Rank rank) {
this.suit = suit;
this.rank = rank;
}
}
/**
* 花色
*/
enum Suit {
spade("♠"), heart("♥"), club("♣"), dianmond("♦"),
;
private final String symbol;
Suit(String symbol) {
this.symbol = symbol;
}
}
/**
* 牌面
*/
enum Rank{
ace("A"),two("2"),three("3"),four("4"),
five("5"),six("6"),seven("7"),eight("8"),nine("9"),
ten("10"),jack("J"),queen("Q"),king("K")
;
private final String symbol;
Rank(String symbol) {
this.symbol = symbol;
}
}
}