I have a Guava Multiset<Integer>
and would like to iterate independently through entries sorted on (a) element value and (b) element count. I have used Simplest way to iterate through a Multiset in the order of element frequency? as
ImmutableMultiset<Integer> entryList = Multisets.copyHighestCountFirst(myIntegerMultiset);
for (Integer i : entryList) {
System.out.println("I"+i);
}
but this returns all entries, whereas I would like a sorted list of Multiset.Entry<Integer>
(one per unique value) which would allow me to get the count.
Independently I would like to get the same list of Multiset.Entry<Integer>
sorted by the value of <Integer>
.
Iterable<Multiset.Entry<Integer>> entriesSortedByCount =
Multisets.copyHighestCountFirst(multiset).entrySet();
Iterable<Multiset.Entry<Integer>> entriesSortedByValue =
ImmutableSortedMultiset.copyOf(multiset).entrySet();
Basically, you just need the entrySet()
, instead of iterating over the Multiset
itself.
You could get a set of entries and then sort it however you need.
Here is how you get a set of entries:
Set<Multiset.Entry<Integer>> entries = myIntegerMultiset.entrySet();
And then to sort we can define two comparators:
Comparator<Multiset.Entry<Integer>> byCount = new Comparator<Multiset.Entry<Integer>>() {
int compare(Multiset.Entry<Integer> e1, Multiset.Entry<Integer> e2) {
return e2.getCount() - e1.getCount();
}
}
Comparator<Multiset.Entry<Integer>> byValue = new Comparator<Multiset.Entry<Integer>>() {
int compare(Multiset.Entry<Integer> e1, Multiset.Entry<Integer> e2) {
return e2.getElement() - e1.getElement();
}
}
Then you can provide the comparators to a tree set to get a sorted collection:
Set<Multiset.Entry<Integer>> entries = myIntegerMultiset.entrySet();
Set<Multiset.Entry<Integer>> entriesSortedByCount = Sets.newTreeset(byCount);
entriesSortedByCount.addAll(entries);
Set<Multiset.Entry<Integer>> entriesSortedByValue = Sets.newTreeset(byValue);
entriesSortedByValue.addAll(entries);
Actually, Louis Wasserman's answer is much better, but I will post this one too in case you wanted to customize your sorting.
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