Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort guava Multimap keys in reverse order?

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.

like image 490
Shamik Avatar asked Feb 16 '16 07:02

Shamik


People also ask

Does Multimap maintain order?

One important thing to note about multimap is that multimap keeps all the keys in sorted order always.

How to sort HashMap in descending order by value in Java?

In order to sort in decreasing order, just reverse the order of Comparator using Collections. reverseOrder() or Comparator. reverse() method of Java 8.

What is guava Multimap?

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.

What is TreeMultimap?

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.


1 Answers

Try using treeKeys(Comparator):

MultimapBuilder.treeKeys(DESC_ORDER).arrayListValues().build();
like image 84
Tagir Valeev Avatar answered Oct 14 '22 02:10

Tagir Valeev