Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a Guava Multiset on entry value and count?

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>.

like image 691
peter.murray.rust Avatar asked Sep 30 '13 17:09

peter.murray.rust


2 Answers

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.

like image 158
Louis Wasserman Avatar answered Nov 15 '22 00:11

Louis Wasserman


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.

like image 22
siledh Avatar answered Nov 14 '22 23:11

siledh