请帮我找一个解决方案,以循环/负载均衡的方式从多个请求(UserRequest(userId,timestamp))生成排序LinkedList<UserRequest>
?
假设我们有多个用户的多个请求列表(XY,其中X:userId,Y:timestamp):
A1,A2,A3,B1,C4,C6 ....
如何将其分类为:
A1,B1,C4,(所有用户最早的要求)
A2,C6,(所有用户的新要求)
A3 ??? (来自所有用户的最新请求)
我已尝试使用LinkedHashMap<userid, LinkedList<timestamp>>
但是现在几天都没有达到效率:
@Test
public void testRequestSorting() throws Exception {
Collection<UserRequest> userRequests = new LinkedList<>(Arrays.asList(
new UserRequest("A", 1),
new UserRequest("A", 2),
new UserRequest("A", 3),
new UserRequest("B", 1),
new UserRequest("C", 4),
new UserRequest("C", 6)
));
Map<String, LinkedList<Long>> groups = new LinkedHashMap<>();
for (UserRequest userRequest : userRequests) {
LinkedList<Long> group = groups.get(userRequest.getUserId());
if (group == null) {
group = new LinkedList<>();
groups.put(userRequest.getUserId(), group);
}
group.add(userRequest.getTimestamp());
}
LinkedList<UserRequest> sortedRequests = new LinkedList<>();
while (!groups.isEmpty()) {
for (Iterator<String> iterator = groups.keySet().iterator(); iterator.hasNext();){
String userId = iterator.next();
LinkedList<Long> timestamps = groups.get(userId);
if (!timestamps.isEmpty()) {
Long first = timestamps.getFirst();
sortedRequests.add(new UserRequest(userId, first));
timestamps.remove(0);
if (timestamps.isEmpty()) {
iterator.remove();
}
}
}
}
for (UserRequest sortedRequest : sortedRequests) {
System.out.println(sortedRequest.getUserId() + "->" + sortedRequest.getTimestamp());
}
}
class UserRequest {
private final String userId;
private final long timestamp;
public UserRequest(String userId, long timestamp) {
this.userId = userId;
this.timestamp = timestamp;
}
public String getUserId() {
return userId;
}
public long getTimestamp() {
return timestamp;
}
}