-
Notifications
You must be signed in to change notification settings - Fork 829
Expand file tree
/
Copy pathCars.java
More file actions
77 lines (62 loc) · 2 KB
/
Copy pathCars.java
File metadata and controls
77 lines (62 loc) · 2 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
package racingcar.domain;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Cars {
private static final String DUPLICATE_NAME_ERROR = "자동차 이름은 중복될 수 없습니다.";
private final List<Car> cars;
public Cars(List<Car> cars) {
validateCars(cars);
this.cars = new ArrayList<>(cars);
}
private void validateCars(List<Car> cars) {
if (cars == null || cars.isEmpty()) {
throw new IllegalArgumentException("자동차 목록은 비어있을 수 없습니다.");
}
validateDuplicateNames(cars);
}
private void validateDuplicateNames(List<Car> cars) {
List<String> names = cars.stream()
.map(car -> car.getName().getName())
.collect(Collectors.toList());
long uniqueNameCount = names.stream()
.distinct()
.count();
if (uniqueNameCount != names.size()) {
throw new IllegalArgumentException(DUPLICATE_NAME_ERROR);
}
}
public void moveAll() {
for (Car car : cars) {
car.move();
}
}
public List<Car> getCars() {
return Collections.unmodifiableList(cars);
}
public List<Car> getWinners() {
int maxPosition = getMaxPosition();
return cars.stream()
.filter(car -> car.isAtPosition(maxPosition))
.collect(Collectors.toList());
}
private int getMaxPosition() {
return cars.stream()
.mapToInt(Car::getPosition)
.max()
.orElse(0);
}
public int size() {
return cars.size();
}
public Car get(int index) {
return cars.get(index);
}
@Override
public String toString() {
return cars.stream()
.map(Car::toString)
.collect(Collectors.joining("\n"));
}
}