Assume you have something like
class Person {
LocalDate bornOn;
LocalDate diedOn;
}
let's say you have a bunch of "Person" instances that you can store any way you like.
What's the best way of writing an efficient function that can list all people that were alive at a given time?
The data structure should be efficiently mutable as well, in particular in terms of adding new elements.
I.e. conceptually something like
List<Person> alive(List<Person> people, LocalDate date) {
return people.stream().filter(x -> x.bornOn.compareTo(date) <= 0 && x.diedOn.compareTo(date) > 0).collect(Collectors.toList())
}
Only more efficient.
My first gut feeling would be having two NavigableMaps
NavigableMap<LocalDate, Person> peopleSortedByBornOn;
NavigableMap<LocalDate, Person> peopleSortedByDiedOn;
each could be queried with headMap() / tailMap() of the given date, and the intersection of those queries would be the result.
Is there any faster, or significantly more convenient solution though? Maybe even some sort of widely used Java collection/map type that'd support such an operation?