I'm fairly new to Guava API and is trying to sort the keys of a MultiMap
in reverse order or descending value. I'm initiating the Map
in the following way:
ListMultimap<Date, Map<String, String>> listMultimap = MultimapBuilder.treeKeys().arrayListValues().build();
This sorts the keys in ascending. E.g.:
List multi map iteration: key -->Fri Jan 01 00:00:00 PST 2016 values -->[{test2=testval2}, {test3=testval3}]
List multi map iteration: key -->Sun Jan 01 00:00:00 PST 2017 values -->[{test1=testval1}]
List multi map iteration: key -->Mon Jan 01 00:00:00 PST 2018 values -->[{test0=testval0}]
List multi map iteration: key -->Tue Jan 01 00:00:00 PST 2019 values -->[{test4=testval4}]
I tried creating a custom Date Comparator
with TreeMultiMap
, but haven't figure a way to do it. This is not syntactically right,but just trying to demonstrate the idea.
static final Comparator<Date> DESC_ORDER = new Comparator<Date>() {
public int compare(Date e1, Date e2) {
return e2.compareTo(e1);
}
};
SortedSetMultimap<Date, Map<String, String>> treeMultimap = TreeMultimap.create(DESC_ORDER);
Any pointers will be appreciated.
One important thing to note about multimap is that multimap keeps all the keys in sorted order always.
In order to sort in decreasing order, just reverse the order of Comparator using Collections. reverseOrder() or Comparator. reverse() method of Java 8.
It is a collection that maps keys to values, similar to java. util. Map, but in which each key may be associated with multiple values.
The TreeMultimap is a variation of a Map in which multiple values or objects are associated with a single key but it will return a sorted list of objects according to their natural ordering without any duplicate key/value pairs.
Try using treeKeys(Comparator)
:
MultimapBuilder.treeKeys(DESC_ORDER).arrayListValues().build();
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