forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListSortCards.java
More file actions
63 lines (51 loc) · 1.21 KB
/
ListSortCards.java
File metadata and controls
63 lines (51 loc) · 1.21 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
package com.zetcode;
import java.util.Comparator;
import java.util.List;
// sorting a list of objects by external comparator
public class ListSortCards {
public static void main(String[] args) {
var cards = List.of(
new Card(Rank.KING, Suit.DIAMONDS),
new Card(Rank.FIVE, Suit.HEARTS),
new Card(Rank.ACE, Suit.CLUBS),
new Card(Rank.NINE, Suit.SPADES),
new Card(Rank.JACK, Suit.SPADES),
new Card(Rank.JACK, Suit.DIAMONDS));
var sorted = cards.stream().sorted(CardComparator.build()).toList();
sorted.forEach(System.out::println);
}
}
enum Rank {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE,
}
enum Suit {
CLUBS,
DIAMONDS,
HEARTS,
SPADES
}
record Card(Rank rank, Suit suit) {
}
class CardComparator implements Comparator<Card> {
static CardComparator build() {
return new CardComparator();
}
@Override
public int compare(Card o1, Card o2) {
return Comparator.comparing(Card::rank)
.thenComparing(Card::suit)
.compare(o1, o2);
}
}