仅在 Java 中对键进行排序的多映射
我希望有一个仅根据键排序的。不应对值进行排序。我试图用番石榴构建一些东西,但我不能使用它,因为值类型没有实现。c.g.c.c.Multimap
TreeMultimap
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;
}
}
我考虑过获取一个密钥,然后迭代排序集中的每个密钥以获取各种值,但我希望使用Guava中现有的(尚未发现的)功能,而不是使用这种黑客。SortedSet
注意:我不会实现,因为它对我的实际对象没有意义。MyObject
Comparable
输入/输出示例:
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