Reputation: 1355
I already saw this question and answer here, but my use case is doing it at creation process.
I can create a multimap like that :
ImmutableListMultimap<Foo, Bar> indexMultiMap = Multimaps.index(barCollection, new Function<Bar, Foo>() {
@Override
public Foo apply(Bar bar) {
//some works
return Foo;
}
});
I know that Foo elements will be unique, and i want to sort this map by frequency of each Foo element size of Bar collection of each Foo element) in this map, descending.
1) How can i do that with one iteration ? Like doing it when indexing this collection to MultiMap
2) If not so, what is the efficient way to get it ?
My objective is at all, when i am iterating this map, i want to see first key has the bigger count of values, like
Foo -> 3 (size of bar collection corresponding to this key)
Foo -> 3
Foo -> 2
Foo -> 1
Foo -> 1
Upvotes: 3
Views: 1530
Reputation: 2441
As @px5x2 said. when you call Multimaps.index()
, keys appear in the order they are first encountered. So, sort your collection first. Using the Guava Multimaps.index()
example here with tiny modification.
ImmutableSet<String> digits = ImmutableSet.of("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine");
Function<String, Integer> lengthFunction = new Function<String, Integer>(){
public Integer apply(String input) {
return input.length();
}
};
ImmutableMultimap<Integer, String> sortedOnLength = Multimaps.index(
Ordering.natural().onResultOf(lengthFunction).sortedCopy(digits),
lengthFunction
);
Upvotes: 2
Reputation: 1565
From javadoc of Multimaps.index()
;
"In the returned multimap, keys appear in the order they are first encountered ..."
If the collection is sorted in a way that 'simulates' implicit sorting behaviour, multimap will be created in the order you want. eg:
SortedMultiset preSorted = TreeMultiset.create(fooComparator);
then feed Multimaps.index()
with above preSorted collection.
Upvotes: 1