0

我有这门课Log

private Integer id;

private Timestamp time;

private String value;

我想生成关于这些间隔的平均值的报告:seconds, minutes, hours, days, months, years. 例如,我在 a 中有这些值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

你们知道我该怎么做吗?

4

1 回答 1

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()));
}

在这里,我假设您仍然希望TimeStampLog构造函数中使用,但不介意在内部将其存储为 JodaTimeDateTime对象。然后我们创建一些假日志。然后我们遍历所有日志并将计数和总数存储到最近的分钟。实际上,我会创建一个对象来存储这些数据(包括总数和计数),然后将其DateTime用作键。我希望这是有道理的。

于 2012-04-28T09:10:13.780 回答