Skip to content

Sum int values in unsorted ArrayList based on dates

I’ve got a list of objects with LocalDateTime and int fields. Here is an example of an object from the list:

   new CustomObject(LocalDateTime.of(2020, Month.MARCH, 01, 06, 0), 20)

How to check whether a sum of ints on a certain date (multiple entries for the same date possible) does not exceed some value for O(n) or better? forEach loop must be used, sorting is restricted.



I’ve done this task by writing a comparator for dates and sorting the incoming list. However, this was O(n^2) and thus unacceptable. I struggled with defining proper (K, V) for a map and @Andreas gave me a clue.

There is not much to be added to his answer – I filled the map and summed ints for each LocalDate in a map.

User contributions licensed under: CC BY-SA
4 People found this is helpful