简体   繁体   中英

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. The values on this line Set<Date> keys = date.keySet(); are 10.31.18 and 11.17.18. I would expect lastDate to equal 11.17.18 however it equals 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 set

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; others, like the HashMap class, do not.

And apparently the Map date doesn't guarantee a specific order. This applies also to Set<Date> keys = date.keySet() as this

Returns a Set view of the keys contained in this map ... is backed by the map ...

But the solution is simple and comes out of the box:

Date lastDate = Collections.max(keys);

This works at once because Date implements Comparable .

Are you using LinkedHashMap or HashMap?

HashMap is not ordered Map. LinkedHashMap is ordered Map which reserves insert order.

But I think you should use TreeSet which can sort your dates. As a result you don't need to care about what kind of Map :)

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