Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a Map by key (date,string)

Map<XMLGregorianCalendar, String> SortedByTimeForJourney = new HashMap<XMLGregorianCalendar, String>();

I have to sort it by key(XMLGregorianCalendar). I tried this

 SortedByTimeForJourney.entrySet().stream().sorted(Map.Entry.<XMLGregorianCalendar, String>comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));

but it is showing Type Parameter 'javax.xml.datatype.XMLGregorianCalendar' is not withing its bound; should implement 'java.lang.Comparable'

I also tried to do by saving it in LinkedHashMap and also using Collections.util method but unable to do.

Someone Please Help me.

like image 487
sandeep gaur Avatar asked Dec 17 '22 15:12

sandeep gaur


1 Answers

To sort a Map by key, use a TreeMap.

As the javadoc says:

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

Since XMLGregorianCalendar doesn't implement Comparable, i.e. doesn't have a natural ordering, you have to specify a Comparator in the constructor.

In Java 8+, use:

new TreeMap<>(XMLGregorianCalendar::compare)

In older versions of Java, use:

new TreeMap<>(new Comparator<XMLGregorianCalendar>() {
    @Override
    public int compare(XMLGregorianCalendar cal1, XMLGregorianCalendar cal2) {
        return cal1.compare(cal2);
    }
})
like image 192
Andreas Avatar answered Jan 02 '23 21:01

Andreas