简体   繁体   中英

Java - Search a List of Objects for a date between 2 dates

I have a sorted List of objects(From is Sorted): List LocationDetail

---------------------------------------------------------------------------------------------
| id | Place      | Name   | From                  | To                   | Address
---------------------------------------------------------------------------------------------
| 2  | Office     | Mark   | 2020-06-02 08:00:00   | 2020-06-02 19:59:59  | Office_Address  |  
| 4  | Office     | John   | 2020-06-02 08:00:00   | 2020-06-02 19:59:59  | Office_Address  |  
| 1  | Home       | Mark   | 2020-06-01 20:00:00   | 2020-06-02 07:59:59  | Home_Address    |  
| 3  | Home       | John   | 2020-06-01 20:00:00   | 2020-06-02 07:59:59  | Home_Address    |
---------------------------------------------------------------------------------------------

I want to search details for the following:

Place, Name, locationTime

If locationTime falls between From and To, Return the row. ( Place, Name, From and To combination is Unique )

My Solution:

  1. Extracted the List of property From to a List fromTimes
  2. Wrote a custom binary search implementation: method LocalDateTime[] getFirstLastIndex(List fromTimes, LocalDateTime locationTime) This method returns the first and last index of the locationTime (for duplicate values(From))
  3. Search the List If firstIndex > listSize/2 firstIndex = firstIndex, LastIndex = listSize-1 If firstIndex < listSize/2 firstIndex = firstIndex, LastIndex = listSize-1 (Also the same)

My Question:
Is there a better solution?

Since you don't need to keep duplicates in your list, I would try to trade it for a TreeSet or a TreeMap , which provide methods like subset(fromElement, toElement) and submap(fromKey, toKey) respectively -- two flavours each, declared in SortedSet/NavigableSet and SortedMap/NavigableMap, so you can control, if needed, whether the from and two are inclusive or exclusive.

It is not exactly straightforward (but still worth pursuing), because:

  • with a Set you need to create two LocationDetail objects to use as "from" and "to" in your query
  • with a Map (keyed by the "from" value), you need to handle the case where multiple location details have the same "from" time. So you will probably need to store some Collection of location details for each "from" value and do some flatMap on the returned submap(from, to).values().stream()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM