[英]I am trying to get the last date element in a set, however It keeps returning the first one?
Below is my code, I get the keys of my Map and then I iterate through them in order to get the last date, However it does not appear to get the last date. 下面是我的代码,我获取了Map的键,然后遍历它们以获取最后一个日期,但是它似乎没有得到最后一个日期。 The values on this line Set<Date> keys = date.keySet();
这行上的值Set<Date> keys = date.keySet();
are 10.31.18 and 11.17.18. 是10.31.18和11.17.18。 I would expect lastDate to equal 11.17.18 however it equals 10.31.18. 我希望lastDate等于11.17.18,但等于10.31.18。 Any ideas what I am doing wrong here. 任何想法我在这里做错了。
Map<Date, List<Integer>> date = date(dates, noPupils);
Set<Date> keys = date.keySet();
for (Iterator<Date> it = keys.iterator(); it.hasNext();) {
while (it.hasNext()) {
Date lastDate = it.next();
It seems you followed this answer . 看来您遵循了这个答案 。 It already says: 它已经说:
A
Collection
is not a necessarily ordered setCollection
不一定是有序集合
In your case it doesn't work because 在您的情况下,它不起作用, 因为
The order of a map is defined as the order in which the iterators on the map's collection views return their elements. 映射的顺序定义为映射的集合视图上的迭代器返回其元素的顺序。 Some map implementations, like the
TreeMap
class, make specific guarantees as to their order; 一些地图实现(例如TreeMap
类)对其顺序做出特定的保证。 others, like theHashMap
class, do not. 其他的(例如HashMap
类)则没有。
And apparently the Map
date
doesn't guarantee a specific order. 显然, Map
date
不能保证特定的订单。 This applies also to Set<Date> keys = date.keySet()
as this 这也适用于Set<Date> keys = date.keySet()
,
因为这
Returns a
Set
view of the keys contained in this map ... is backed by the map ... 返回此映射中包含的键的Set
视图...由映射支持...
But the solution is simple and comes out of the box: 但是解决方案很简单,可以立即使用:
Date lastDate = Collections.max(keys);
This works at once because Date
implements Comparable
. 由于Date
实现Comparable
因此可以立即工作。
Are you using LinkedHashMap or HashMap? 您正在使用LinkedHashMap还是HashMap?
HashMap is not ordered Map. HashMap没有排序的Map。 LinkedHashMap is ordered Map which reserves insert order. LinkedHashMap是有序地图,保留插入顺序。
But I think you should use TreeSet which can sort your dates. 但是我认为您应该使用TreeSet来对日期进行排序。 As a result you don't need to care about what kind of Map :) 因此,您无需关心哪种Map :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.