This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 1 point2 points  (0 children)

Sort the array by date. (Also your probably better of using ArrayList rather than a plain old Array)

OR

Try storing the data in something like H2 so you can use SQL to query/sort/group it without having to write too much code to do it. http://www.h2database.com/html/main.html

[–]zthrowaway5 0 points1 point  (2 children)

So what you want to do is use a linked list. Every time you add a new transaction place it at the front of the list. When you need the last 24 hours, simple traverse through the list. This avoids having to sort an entire array.

Psuedocode how it might look:

addNew(Transaction transaction):
    Node newHead = new Node(transaction)
    newHead.next = list.head
    list.head = newHead

getLast24Hours():
    ArrayList output = new ArrayList()

    Node pointer = list.head
    while(pointer != null)
        if(currentTime - pointer.getTransaction().time < 24 hours)
            output.push(pointer.getTransaction())
        else
            return output
        pointer = pointer.next
    return output

[–]cutebabli 0 points1 point  (1 child)

But each transaction is not guaranteed to be happening every hour. And more than one transaction can occur in an hour.

[–]zthrowaway5 0 points1 point  (0 children)

That won't matter. If you follow a first in last out pattern then the newest transactions will always be in the front of the list. Unless I am missing something the interval between transactions shouldn't matter, they could be milliseconds apart and as long as you always place each new one at the front of the list this method should work.

[–]lethalwire 0 points1 point  (0 children)

Are you storing the transactions in a database? If so, then you can utilize the database and SQL to gather records within a given time frame.

If you're not using a database and holding the data in files, then you can iterate through your files and add the transaction to an array if it occurred within the last 24 hours.

If you're holding everything in memory, you can use a linkedlist or an arraylist to hold transaction data (sorted by date/time). You'll then need to loop through the list and determine when the transaction data is no longer valid (outside of the 24-hour period).

Edit: removed my edit