好的,这样的事情怎么样(虽然当我看到你还在挣扎时我很快就把它放在一起 - 使用地图来保持计数并不出色):
将日志更改为:
Integer id;
DateTime time;
String value;
public Log(Integer id, Timestamp time, String value) {
this.id = id;
this.time = new DateTime(time.getTime());
this.value = value;
}
然后:
// Build some fake logs
final List<Log> logs = new ArrayList<Log>();
logs.add(new Log(1, new Timestamp(new DateTime().withDate(2011,1,1).getMillis()), "90"));
logs.add(new Log(1, new Timestamp(new DateTime().withDate(2010,1,1).withTimeAtStartOfDay().getMillis()), "60"));
logs.add(new Log(1, new Timestamp(new DateTime().withDate(2010,1,1).withTimeAtStartOfDay().getMillis()), "80"));
logs.add(new Log(1, new Timestamp(new DateTime().withDate(2009,1,1).getMillis()), "70"));
final Map<DateTime, Integer> total = new HashMap<DateTime, Integer>();
final Map<DateTime, Integer> count = new HashMap<DateTime, Integer>();
for(Log l : logs) {
// Round down to the nearest minute
final DateTime t = l.getTime().withSecondOfMinute(0);
Integer sum = total.get(t);
sum = (sum == null) ? 0 : sum;
total.put(t, sum + Integer.parseInt(l.getValue()));
Integer c = count.get(t);
c = (c == null) ? 0 : c;
count.put(t, c + 1);
}
for(Map.Entry<DateTime, Integer> entry : total.entrySet()) {
System.out.println(entry.getValue() / count.get(entry.getKey()));
}
在这里,我假设您仍然希望TimeStamp
在Log
构造函数中使用,但不介意在内部将其存储为 JodaTimeDateTime
对象。然后我们创建一些假日志。然后我们遍历所有日志并将计数和总数存储到最近的分钟。实际上,我会创建一个对象来存储这些数据(包括总数和计数),然后将其DateTime
用作键。我希望这是有道理的。