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
| /**
* 使用者評分排序系統
*/
public class UserRatingSystem {
public static class UserRating {
private final String userId;
private final double averageRating;
private final int totalReviews;
public UserRating(String userId, double averageRating, int totalReviews) {
this.userId = userId;
this.averageRating = averageRating;
this.totalReviews = totalReviews;
}
public double getWeightedScore() {
// 加權評分:考慮評論數量
return averageRating * Math.log(totalReviews + 1);
}
// getter 方法
public String getUserId() { return userId; }
public double getAverageRating() { return averageRating; }
public int getTotalReviews() { return totalReviews; }
@Override
public String toString() {
return String.format("UserRating{userId='%s', avgRating=%.2f, reviews=%d, weighted=%.2f}",
userId, averageRating, totalReviews, getWeightedScore());
}
}
/**
* 根據加權評分排序用戶
*/
public static Map<String, UserRating> sortUsersByRating(Map<String, UserRating> users) {
return users.entrySet()
.stream()
.sorted(Map.Entry.<String, UserRating>comparingByValue(
(r1, r2) -> Double.compare(r2.getWeightedScore(), r1.getWeightedScore())))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue,
LinkedHashMap::new
));
}
public static void main(String[] args) {
Map<String, UserRating> users = new HashMap<>();
users.put("user1", new UserRating("user1", 4.5, 100));
users.put("user2", new UserRating("user2", 4.8, 50));
users.put("user3", new UserRating("user3", 4.2, 200));
users.put("user4", new UserRating("user4", 4.9, 25));
Map<String, UserRating> sortedUsers = sortUsersByRating(users);
System.out.println("Users sorted by weighted rating:");
sortedUsers.values().forEach(System.out::println);
}
}
|
留言討論