Skip to main content
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Efficient way to implement 'events since x' in Java

I want to be-able to ask an object 'how many events have occurred in the last x seconds' where the x is an argument.

e.g. how many events have occurred in the last 120 seconds..

How I approached is linear based on the number of events occurring but was wanting to see what the most efficient way (space & time) to achieve this requirement?;

public class TimeSinceStat {
private List<DateTime> eventTimes = new ArrayList<>();

public void apply() {
            eventTimes.add(DateTime.now());
           }


public int eventsSince(int seconds) {
    DateTime startTime = DateTime.now().minus(Seconds.seconds(seconds));
    for (int i = 0; i < orderTimes.size(); i++) {
        DateTime dateTime = eventTimes.get(i);
        if (dateTime.compareTo(startTime) > 0)
            return eventTimes.subList(i, eventTimes.size()).size();
    }
    return 0;
}

(PS - i'm using JodaTime for the date/time representation)

Edit:

The key of this algorithm to find all events that have happened in the last x seconds; the exact start time (e.g. now - 30 seconds) is may or maynot be in the collection

Answer*

Cancel
3
  • @goat so? TreeMap also has the data sorted and handles the algorithm in O(log n), while using the List approach takes O(n), and its usage would be of 1 line.
    Luiggi Mendoza
    –  Luiggi Mendoza
    2014-06-12 14:41:02 +00:00
    Commented Jun 12, 2014 at 14:41
  • @goat but it's not sorted by event time - OP is recommended to store it in a structure sorted by event time
    eis
    –  eis
    2014-06-12 14:42:13 +00:00
    Commented Jun 12, 2014 at 14:42
  • OP it's storing only the time, not the event, so I think a Set suits better than a Map
    Pablo Lozano
    –  Pablo Lozano
    2014-06-12 14:48:04 +00:00
    Commented Jun 12, 2014 at 14:48

Morty Proxy This is a proxified and sanitized view of the page, visit original site.