Reputation: 79
I have an arraylist filled with timestamps (up to millisec)
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
Each timestamp is a transaction and I need to calculate tps. How do I get a list of list which eventually it would be something like this
2015/11/01 12.12.12, 3
2015/11/01 12.12.12, 2
2015/11/01 12.12.20, 4
where first is the timestamps occurred for one second on second level and 3,2,4 etc is the tps?
Upvotes: 0
Views: 2176
Reputation: 649
You have to use one ArrayList to contain all the timestamps and one new HashMap with a String
as a key and an Integer
as a value where the String
contains timestamps and the Integer
is a counter. like this;
HashMap<String, Integer> hash = new HashMap<>();
Then you have to insert the timestamp and count values in the hashmap using a for
loop after comparing the previous values with current value of the ArrayList
, like this:
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);
Then the key values you have in the hashmap are the results. The code is:
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());
}
Upvotes: 1
Reputation: 41188
Create a class looking something like:
public class TransactionsPerSecond {
long time;
int transactions=1; //Start at 1 to count the initial one
}
Loop through the incoming data. If the time doesn't match the current TransactionsPerSecond object then create a new one, otherwise add 1 to the transactions count for the current one.
// 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++;
}
}
Upvotes: 1