-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStrategy.java
74 lines (62 loc) · 1.81 KB
/
Strategy.java
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
package code;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Strategy {
public static void main(String[] args) {
Item item1 = new Item("item1", 300);
Item item2 = new Item("item3", 200);
Item item3 = new Item("item2", 100);
List<Item> items = new ArrayList<>();
items.add(item1);
items.add(item2);
items.add(item3);
// [Item{name='item1', price=300},
// Item{name='item2', price=100},
// Item{name='item3', price=200}]
items.sort(Item.createByNameComparator());
System.out.println(items);
// [Item{name='item2', price=100},
// Item{name='item3', price=200},
// Item{name='item1', price=300}]
items.sort(Item.createByPriceComparator());
System.out.println(items);
}
}
class Item {
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
public static Comparator<Item> createByNameComparator() {
return new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o1.getName().compareTo(o2.getName());
}
};
}
public static Comparator<Item> createByPriceComparator() {
return new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o1.getPrice() - o2.getPrice();
}
};
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return "Item{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}