fon*_*232 1 java search date hashmap
我有一个问题需要解决,我需要在Java中创建一个会计和簿记解决方案(现在只是后端).他们要求系统存储以前给定产品的价格,所以我决定选择HashMap<Date,Integer>.
现在问题是,系统必须能够在给定时间内检索价格,用于记帐,追溯购买(订单存储物品和购买时间,因此可以轻松回顾).这将是好事,但如果购买日期与价格设置日期不匹配,则简单的get方法返回null.到目前为止,我还没有能够找出在购买日期之前查找第一个上一个日期的搜索方法,以返回价格.
有没有建议的方法来解决这个问题?
我建议你检查一下TreeMap.
要获得最接近的日期,date你可以这样查看:
return map.get(map.headMap(date, true).lastKey());
Run Code Online (Sandbox Code Playgroud)
分解以上:
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());
}
Run Code Online (Sandbox Code Playgroud)
输出:
First
Second
Fifth
Run Code Online (Sandbox Code Playgroud)