我有这个课程Log
:
private Integer id;
private Timestamp time;
private String value;
我想生成有关这些时间间隔内平均值的报告:seconds, minutes, hours, days, months, years
。
例如,我在List<Log> logs
:
代码:
for (Log log : logs)
System.out.println(log.getTime().toString() + " " + log.getValue() + ", ");
输出:
INFO: 2012-04-26 20:06:21.0 10.0,
INFO: 2012-04-27 09:09:32.0 10.0,
INFO: 2012-04-27 09:31:09.0 15.0,
INFO: 2012-04-27 09:31:23.0 27.0,
INFO: 2012-04-27 09:31:42.0 30.0,
INFO: 2012-04-27 09:31:54.0 47.0,
INFO: 2012-04-27 12:19:00.0 80.0,
我想取minutes
中的平均值,结果应为:
10 / 1 = 10,
10 / 1 = 10,
15 + 27 + 30 + 47 = 119/4 = 29.75
80 / 1 = 80
你们有什么想法我能做到这一点吗?
答案 0 :(得分:0)
好的怎么样这样的事情(虽然当我看到你还在苦苦挣扎时我把它快速地扔在一起 - 使用地图来保持计数并不精彩):
将日志更改为:
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
,但不介意将其作为JodaTime DateTime
对象存储在内部。然后我们创建一些假日志。然后,我们遍历所有日志并将计数和总数存储到最近的分钟。实际上,我会创建一个对象来存储这些数据(包括总数和计数),然后使用DateTime
作为关键字。我希望这是有道理的。