我建议你检查一下TreeMap。
要获得最接近的日期,date您可以这样查找:
return map.get(map.headMap(date, true).lastKey());
上面的分解:
previous = map.headMap(date, true)返回所有以前的条目(包括日期)
closestMatchingKey = previous.lastKey()返回该(上方)映射中的最后一个键
map.get(closestMatchingKey)返回匹配项(或者null如果没有)
例子:
public static void main(String[] args) {
TreeMap<Date, String> map = new TreeMap<>();
map.put(new Date(0), "First");
map.put(new Date(10), "Second");
map.put(new Date(20), "Third");
map.put(new Date(30), "Fourth");
map.put(new Date(40), "Fifth");
System.out.println(getClosestPrevious(map, new Date(5)));
System.out.println(getClosestPrevious(map, new Date(10)));
System.out.println(getClosestPrevious(map, new Date(55)));
}
private static String getClosestPrevious(TreeMap<Date, String> map, Date date) {
return map.get(map.headMap(date, true).lastKey());
}
输出:
First
Second
Fifth