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?
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.
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.
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.
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With