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.
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);
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With