Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Guava's MultiMap only by keys?

I have MultiMap from Guava library. I want to sort it only by keys. I have tried:

Multimap<String, MyObj> sortedMultiMap =
    TreeMultimap.create(Ordering.from(new Comparator<String>() {
        @Override
        public int compare(String lhs, String rhs) {
            //my comparison here
        }
    }), Ordering.natural());//i want not to sort values at all,MyObj doesn't implement Comparable
sortedMultiMap.putAll(notSortedMultiMap);

But as you can see, TreeMultiMap.create method has 2 arguments - comparators for keys and values. How i can sort MultiMap only by keys?

like image 679
Lester Avatar asked Mar 28 '16 10:03

Lester


People also ask

Can you sort a Multimap?

Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function Compare , applied to the keys. Search, insertion, and removal operations have logarithmic complexity.

Does Multimap maintain order?

Multimap is similar to a map with the addition that multiple elements can have the same keys. Also, it is NOT required that the key-value and mapped value pair have to be unique in this case. One important thing to note about multimap is that multimap keeps all the keys in sorted order always.

Can a Multimap have a null key?

Implementation of Multimap using hash tables. The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an existing key-value pair has no effect. Keys and values may be null.

How do you create a Multimap?

Another way to create a Multimap is to use the static method create() in the concrete classes that implement the interface (e.g., ArrayListMultimap<K, V> , LinkedListMultimap<K, V> , etc.): ListMultimap<String, Integer> m = ArrayListMultimap. create();


2 Answers

Use MultimapBuilder:

 Multimap<String, MyObj> multimap = 
      MultimapBuilder.treeKeys().linkedListValues().build();
like image 96
Louis Wasserman Avatar answered Oct 12 '22 01:10

Louis Wasserman


Update after answer from Louis Wasserman Even if my original answer solved the problem and answered the question I think this is the more elegant solution.

Multimap<String, MyObj> multimap = 
    MultimapBuilder.treeKeys(/* you comparator here */).linkedListValues().build();

You can use Ordering.arbitrary() as the second argument, it does not require the objects to implement Comparable.

If insertion order is needed you can use something like

Multimap<String, MyObj> sortedMultiMap = Multimaps.newMultimap(
            Maps.<String, Collection<MyObj>>newTreeMap(/* your comparator here*/),
            Lists::newLinkedList);
like image 29
gustf Avatar answered Oct 12 '22 00:10

gustf