简体   繁体   中英

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?

Use MultimapBuilder :

 Multimap<String, MyObj> multimap = 
      MultimapBuilder.treeKeys().linkedListValues().build();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM