散列映射中的散列映射的平均值

时间:2013-03-18 15:02:07

标签: java hashmap simpledateformat

我试图从日志文件中找出用户操作之间的时间平均差异。例如,对于用户操作ua, login, login和下一个用户操作ua, disclaimer ok,我想减去两个操作之间的时间,并且每次特定订单出现时,将这些时间加在一起,除以该模式的出现次数。

这是我的hashmap

Map<String, HashMap<String, NumberHolder>> uaCount =
                        new HashMap<String, HashMap<String, NumberHolder>>();

NumberHolder定义为

private class NumberHolder
{
    public int occurences;
    public int sumtime_in_milliseconds;
}

sCurrentLinesNextLine是他们的名字所表明的。迭代时,sNextLine变为sCurrentLine,等等。

在我的代码中,我遍历日志文件,打开它们,检查行是否是用户操作,声明sCurrentLinesNextLine并拆分这两行以隔离用户操作部分。然后我从两行中分离动作的时间和日期,使用简单的日期格式并解析它们,然后我找到差异。我想要的输出是ua, login, login --> ua, disclaimer, ok AVERAGE = 38 seconds。如果你想查看整个代码,请问。

2 个答案:

答案 0 :(得分:1)

伪代码:

function void addLinePair(string1, string2, deltaTime) {
    // Assumes string1 and string2 have been stripped of variable text

    keyString = string1 + "|" + string2;

    hashValue = findInHashTable(keyString);

    if (hashValue == <not found>) {

      hashValue = new NumberHolder
      insertInHashtable(hashValue, keyString)

    }

    hashValue.sumtime_in_milliseconds += deltaTime
    hashValue.occurrences++
}

function void printAverages {

    for (key,value in hashTable) {
        string1 = first part of key
        string2 = second part of key
        average = (float)value.sumtime_in_milliseconds / (float)value.occurrences
        print (string1 + " --> " + string2 + ", AVERAGE = " + average + " seconds")
    }
}

答案 1 :(得分:0)

在我看来,为什么你使用两级地图并不完全清楚。如果你正在寻找平均时间,你应该通过一个然后再到下一个。即平均时间是基于每一个与之后的时间之间的时间,而不是每一个和每一个之间的时间。

List<String> logLines = new List<String();

//populate logLines

getLogTime(String a, String b){
    long logTimeA = -1;
    long totalLogTime = 0;
    long count;
    for(String logLine : logLines){
        if(logLine.equals(a)){
            logTimeA = parseForTime(logLine);
        }
        else if(logLine.equals(b) && logTimeA >= 0){
            totalLogTime += logTimeA - parseForTime(logLine);
            count++
            logTimeA = -1;
        }
        //if you want it to only do the one immediately after
        else if(!logLine.equals(b)){
            logTimeA = -1;
        }
    }
    if(count == 0){
        return 0;
    }
    return totalLogTime/count;
}
相关问题