简体   繁体   中英

How to sort a HashMap by Keys and then Values?

I have the following HashMap

HashMap<GregorianCalendar, Event> calHash new HashMap<GregorianCalendar, Event>();

I am able to sort it by keys by doing this:

SortedSet<GregorianCalendar> keys = new TreeSet<GregorianCalendar>(calHash.keySet());

I also made my Event class implement Comparable and overwrote the compareTo method as follows:

@Override
    public int compareTo(Object e) {
        // TODO Auto-generated method stub
       int hour = ((Event) e).getStartTime().get(Calendar.HOUR_OF_DAY);
       int minute = ((Event) e).getStartTime().get(Calendar.MINUTE);
       int anotherHour = this.startTime.get(Calendar.HOUR_OF_DAY);
       int anotherMinute = this.startTime.get(Calendar.MINUTE);

       if(anotherHour - hour == 0 ){
           return anotherMinute - minute;
       }else{
           return anotherHour - hour;
       }


    return 0;

    }
}

With the above, I can sort my Events (values) by ascending order. Now my question is, how can I sort my HashMap first by keys and then if the same key has multiple values (events scheduled with different times) sort it my values after that?

I can only seem to find how to sort one way or the other but now a double sort by both.

Use calHash.entrySet() . This will give you a set of Map.Entry , which you can then dump into a new LinkedList<Map.Entry>(entrySet) .

You can then sort that list using Collections.sort(list, comparator) with a custom comparator that sorts those entries by one criteria, and if that criteria is the same, then by the other criteria.

Here's an example anonymous comparator:

Collections.sort(list, new Comparator<Map.Entry>() {
    public int compare(Map.Entry e1, Map.Entry e2) {
       // do comparisons here
       return 0;    
    }
});

A Map can't have multiple entries with the same key so it takes a little more work to sort by keys AND then values.

Perhaps the easiest way would be to make a new Map<GregorianCalendar, List<Event>> where each entry in the Map maps one key to a list of events.

If you have multiple events with the same time, then you would add the event to the list.

You could then sort the list using Collections.sort() .

By the way, you can create a sorted Map using TreeMap instead of creating a Hashmap and then making a separate SortedSet of just the keys.

Map<GregorianCalendar, List<Event>> map = new TreeMap<>();

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