Search code examples
javaguavatreemaps

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?


Solution

  • 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);