5

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?

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
Lester
  • 2,544
  • 4
  • 27
  • 38

2 Answers2

8

Use MultimapBuilder:

 Multimap<String, MyObj> multimap = 
      MultimapBuilder.treeKeys().linkedListValues().build();
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 2
    Nice, I updated my answer with this solution as it was the accepted answer and this solution is more elegant. Hope this is ok for you. – gustf Apr 06 '16 at 20:01
7

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);
gustf
  • 1,959
  • 13
  • 20
  • I have already tried that, but seems that Ordering.arbitrary() just randomly mixes my values after putAll. I need default order, maybe its related to MultiMap Value stored as Collection - but should be LinkedList? – Lester Mar 28 '16 at 10:29
  • Hmm, it is supposed to give the same order during the life of the VM. "There is no meaning whatsoever to the order imposed, but it is constant for the life of the VM". But maybe this does not work in your use case either? – gustf Mar 28 '16 at 10:33
  • 1
    Does "default order" in your case mean "insertion order"? – gustf Mar 28 '16 at 10:34
  • What do you mean by "I need default order"? – The111 Mar 28 '16 at 10:36
  • "Does "default order" in your case mean "insertion order"? - yes. But my notSortedMultiMap was created by Multimaps.index, wich returns ImmutableListMultimap, i can't change container for values – Lester Mar 28 '16 at 10:36
  • 1
    https://github.com/google/guava/issues/1522 (this is the 7th Google result for your question's title) – The111 Mar 28 '16 at 10:42