What collection for quickly finding next elements?

Viewed 34

I have an object with a currentDate field. It will need to access n next workdays. I have a .csv file with all the workdays.

My current solution:

  • Create an ArrayList<LocalDate> workdays from the .csv.
  • Get currentDateIndex from workdays.indexOf(currentDate).
  • Get next n next days by iterating over workdays.get(currentDateIndex + i).

What I don't like about it:

  • No way of ensuring that workdays list is actually sorted, or doesn't have duplicates.
  • O(n) complexity of indexOf method.

Is there a collection that will ensure that the workdays are unique and sorted and that can quickly return next n workdays when given the currentDate?

1 Answers

Use a TreeSet<LocalDate>. That will keep the dates unique and sorted.

And you can obtain the next dates by calling tailSet(E fromElement, boolean inclusive), and iterate over the returned Set to get the next n elements following a given element.

Related