使用java计算时间戳中每秒的事务数



我有一个数组列表,里面充满了时间戳(最多毫秒)

2015/11/01 12.12.12.990
2015/11/01 12.12.12.992
2015/11/01 12.12.12.999
2015/11/01 12.12.15.135
2015/11/01 12.12.15.995
2015/11/01 12.12.20.135
2015/11/01 12.12.20.200
2015/11/01 12.12.20.300
2015/11/01 12.12.20.900

每个时间戳都是一个事务,我需要计算tps。我如何获得一个列表,它最终会像这个一样

2015/11/01 12.12.12, 3
2015/11/01 12.12.12, 2
2015/11/01 12.12.20, 4

其中,第一个是在第二级上发生的一秒钟的时间戳和3,2,4等是tps?

您必须使用一个ArrayList来包含所有时间戳,并使用一个以String为键、以Integer为值的新HashMap,其中String包含时间戳,Integer是计数器。像这样;

HashMap<String, Integer> hash = new HashMap<>();

然后,在比较ArrayList的先前值和当前值之后,您必须使用for循环在哈希图中插入时间戳和计数值,如下所示:

if(i>0 && al.get(i).substring(0, 19).equalsIgnoreCase(al.get(i-1).substring(0, 19)))
hash.put(al.get(i).substring(0, 19),count);

然后你在hashmap中的键值就是结果。代码为:

ArrayList<String> al = new ArrayList<String>();
    al.add("2015/11/01 12.12.12.990");
    al.add("2015/11/01 12.12.12.992");
    al.add("2015/11/01 12.12.12.999");
    al.add("2015/11/01 12.12.15.135");
    al.add("2015/11/01 12.12.15.995");
    al.add("2015/11/01 12.12.20.135");
    al.add("2015/11/01 12.12.20.200");
    al.add("2015/11/01 12.12.20.300");
    al.add("2015/11/01 12.12.20.900");
    HashMap<String, Integer> hash = new HashMap<>();
    int count = 0;
    for(int i=0;i<al.size();i++){
        if(i>0 && al.get(i).substring(0, 19).equalsIgnoreCase(al.get(i-1).substring(0, 19)))
            hash.put(al.get(i).substring(0, 19),++count);
        else
            hash.put(al.get(i).substring(0, 19),count=1);
    }
    for (Entry<String, Integer> entry : hash.entrySet()) {
        System.out.println(entry.getKey()+","+entry.getValue());
    }

创建一个类似的类

public class TransactionsPerSecond {
    long time;
    int transactions=1; //Start at 1 to count the initial one
}

循环处理传入的数据。如果时间与当前TransactionsPerSecond对象不匹配,则创建一个新对象,否则在当前对象的事务计数中添加1。

// For you to do, create results arraylist.
TransactionsPerSecond current = null;
for (String str: inputData) {
   // for you to do - parse str into a Date d.
   Date d = ???;
   if (current == null || d.getTime() != current.time) {
      current = new TransactionsPerSecond();
      current.time = d.getTime();
      results.add(current);
   } else {
      current.transactions++;
   }
}

最新更新