[英]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. 我有一个Guava
Multiset<Integer>
并希望通过(a)元素值和(b)元素计数排序的条目独立迭代。 I have used Simplest way to iterate through a Multiset in the order of element frequency? 我用Simplest方式按元素频率的顺序迭代Multiset? 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. 但这会返回所有条目,而我想要一个
Multiset.Entry<Integer>
的排序列表(每个唯一值一个),这将允许我得到计数。
Independently I would like to get the same list of Multiset.Entry<Integer>
sorted by the value of <Integer>
. 独立我想获得的同一列表
Multiset.Entry<Integer>
通过的值排序<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. 基本上,您只需要
entrySet()
,而不是迭代Multiset
本身。
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. 实际上,Louis Wasserman的答案要好得多,但我也会发布这个,以防你想要自定义排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.