Reputation: 2584
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?
Upvotes: 5
Views: 4078
Reputation: 2017
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);
Upvotes: 7
Reputation: 198163
Use MultimapBuilder
:
Multimap<String, MyObj> multimap =
MultimapBuilder.treeKeys().linkedListValues().build();
Upvotes: 8