使Multimap仅在Java中按键排序 [英] Having a Multimap sorted on keys only in Java
问题描述
我想要一个仅基于键排序的 c.g.c.c.Multimap
。不应对值进行排序。我试图用guava的 TreeMultimap
构建一些东西,但我不能使用它,因为值类型没有实现 Comparable
。
I would like to have a c.g.c.c.Multimap
that is sorted based on keys only. The values shouldn't be sorted. I've tried to build something with guava's TreeMultimap
, but I can't use it because the value type doesn't implement Comparable
.
public class MyObject /* doesn't implement Comparable */ {
private String name;
private int score;
// Getters/setters are implemented
public static Function<MyObject,Integer> myObjectToScore {
@Override public Integer apply (MyObject o) { return o.score; }
}
public static Multimap<Integer,MyObject> indexOnScore(Iterable<MyObject> i) {
Multimap<Integer,MyObject> m = Multimaps.index(i, myObjectToScore());
// Do the sort of the keys.
return m;
}
}
我考虑过获得 SortedSet
的键,然后遍历排序集中的每个键以获取各种值,但我希望在Guava中使用现有的(但未发现的)功能而不是使用这种 hack 。
I've thought about getting a SortedSet
of the keys, then iterating over each of these keys in the sorted set to fetch the various values, but I was hoping using an existing (yet undiscovered) feature in Guava rather than using this kind of hack.
注意:我不会让 MyObject
实现可比较
因为它对我的实际对象毫无意义。
Note: I won't make MyObject
implement Comparable
because it makes no sense with my actual object.
输入示例/ output:
Example of input/output:
Set<MyObject> s = Sets.newHashSet(
new MyObject("a", 2),
new MyObject("b", 3),
new MyObject("c", 1),
new MyObject("d", 3),
new MyObject("e", 1)
); // Assuming constructor MyObject(String name, int score)
for (Map.Entry<Integer, MyObject> e: MyObject.indexedOnScore(s).entries()) {
System.out.printf("%d -> %s%n", e.getKey(), e.getValue().getName());
}
打印:
1 -> c // or switched with line below
1 -> e
2 -> a
3 -> b // or switched with line below
3 -> d
推荐答案
Multimaps.index
返回 ImmutableListMultimap
,因此在创建它之后将无法对其进行排序。但是,您可以先创建 Iterable< MyObject>
的排序副本,然后将其输入 Multimap.index
。 .. ImmutableListMultimap
保持事物的顺序与它们相同。
Multimaps.index
returns an ImmutableListMultimap
, so you wouldn't be able to sort it after creating it. You could, however, first create a sorted copy of your Iterable<MyObject>
and feed that to Multimap.index
... ImmutableListMultimap
keeps things in the same order it was given them.
public static ImmutableMultimap<Integer, MyObject> indexOnScore(Iterable<MyObject> i) {
List<MyObject> sorted = Ordering.natural().onResultOf(myObjectToScore())
.sortedCopy(i);
return Multimaps.index(sorted, myObjectToScore());
}
另一种选择可能是创建 TreeMultimap
并使用 Ordering.arbitrary()
作为值的比较器
。
Another option might be to create a TreeMultimap
and use Ordering.arbitrary()
as the Comparator
for the values.
这篇关于使Multimap仅在Java中按键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!