我有一个问题要解决,我需要用Java创建一个会计和记账解决方案部分(目前只是后端)。它们需要系统存储给定产品的先前价格,所以我决定使用HashMap<Date,Integer>。
现在的问题是,系统必须能够检索给定时间的价格,以便记账,跟踪购买(订单存储商品和购买时间,以便可以轻松地进行查看)。这一切都很好,但是如果购买日期与价格设置日期不匹配,那么简单的get方法将返回null。到目前为止,我还无法找到一种搜索方法,该方法查找购买日期之前的第一个日期,以返回价格。
有什么建议的方法来解决这个问题吗?
发布于 2012-12-08 19:50:24
我建议你去看看TreeMap。
要在date之前获得最近的日期,您可以像这样查找它:
return map.get(map.headMap(date, true).lastKey());以上内容的详细介绍:
previous = map.headMap(date, true)返回之前的所有条目(包括date)closestMatchingKey = previous.lastKey()返回其中的最后一个键) mapmap.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发布于 2012-12-08 20:11:45
您需要的是使用TreeMap,特别是NavigableMap#foorEntry方法(我强调):
公共Map.Entry floorEntry(K密钥)
从接口复制的描述: NavigableMap返回与最大键相关联的键值映射,小于或等于给定的键,如果没有这样的键,则返回null。
由:接口NavigableMap中的floorEntry指定
发布于 2012-12-08 19:51:37
据我所知,你地图的关键字是日期。如果是这样,我建议您使用TreeMap而不是HashMap,并使用实现“最近”日期逻辑的自定义比较器。比较器的方法compare()将在date足够接近时返回0,而不需要精确匹配。
https://stackoverflow.com/questions/13777147
复制相似问题