根据键和忽略值对 TreeMultiMap 进行排序
Sorting TreeMultiMap based on key and ignore value
所以我做了一些研究,得出的结论是我需要使用多树图,当我使用树图时,它允许我根据键进行排序,但是我需要多个值,虽然使用树图可以解决问题。
我的目标是根据用户的优先级对用户进行排序,但是大多数用户的默认优先级为 0,其中一个优先级高于其他用户(这就是我需要多图的原因)。但是我没有弄清楚如何构建 TreeMultiMap。
我从来没有真正用比较器做过任何工作,这是我现在的主要问题。我希望有人能给我指出正确的方向,或者完全可以让我解决问题的方向。
请注意,我确实想到了 TreeMap<Integer, List<Entry>>
,但我不想使用它,因为它看起来很乱,而且我确信有更好、更简单的方法来实现我需要的东西。
谢谢
Guava 的 Multimap
implementations does not have public constructors, hence the problem with "erroring" - you should use static methods (namely create
in each implementation) to construct an instance of the multimap. You're probably interested in TreeMultimap.create()
(not no capital "m" in "map"), which creates SortedSetMultimap
,大致相当于 TreeMap<K, TreeSet<V>>
。例如:
SortedSetMultimap<Integer, String> multimap = TreeMultimap.create();
multimap.put(0, "zero");
multimap.put(0, "nought");
multimap.put(1, "one");
System.out.println(multimap);
// prints: {0=[nought, zero], 1=[one]}
另一方面,如果您不想(或不能)对值进行排序,您可以使用自定义多图,可以使用 MultimapBuilder
:
创建
ListMultimap<Integer, Entry> multimap =
MultimapBuilder.treeKeys().arrayListValues().build();
因此,根据 Xaerxess 提供的信息,我决定研究 Guava 提供的其他地图和实现,但找到了一种基于树图创建排序多重地图的方法。
然后我使用了一个逆序比较器,它允许我根据需要对值进行排序。感谢其他人,他们对信息发表了评论,因为它非常有帮助。
我最终使用的代码如下:
Multimap<Integer, Entry> sortedMap = Multimaps.newListMultimap(new TreeMap<>(Collections.reverseOrder()), Lists::newArrayList);
所以我做了一些研究,得出的结论是我需要使用多树图,当我使用树图时,它允许我根据键进行排序,但是我需要多个值,虽然使用树图可以解决问题。
我的目标是根据用户的优先级对用户进行排序,但是大多数用户的默认优先级为 0,其中一个优先级高于其他用户(这就是我需要多图的原因)。但是我没有弄清楚如何构建 TreeMultiMap。
我从来没有真正用比较器做过任何工作,这是我现在的主要问题。我希望有人能给我指出正确的方向,或者完全可以让我解决问题的方向。
请注意,我确实想到了 TreeMap<Integer, List<Entry>>
,但我不想使用它,因为它看起来很乱,而且我确信有更好、更简单的方法来实现我需要的东西。
谢谢
Guava 的 Multimap
implementations does not have public constructors, hence the problem with "erroring" - you should use static methods (namely create
in each implementation) to construct an instance of the multimap. You're probably interested in TreeMultimap.create()
(not no capital "m" in "map"), which creates SortedSetMultimap
,大致相当于 TreeMap<K, TreeSet<V>>
。例如:
SortedSetMultimap<Integer, String> multimap = TreeMultimap.create();
multimap.put(0, "zero");
multimap.put(0, "nought");
multimap.put(1, "one");
System.out.println(multimap);
// prints: {0=[nought, zero], 1=[one]}
另一方面,如果您不想(或不能)对值进行排序,您可以使用自定义多图,可以使用 MultimapBuilder
:
ListMultimap<Integer, Entry> multimap =
MultimapBuilder.treeKeys().arrayListValues().build();
因此,根据 Xaerxess 提供的信息,我决定研究 Guava 提供的其他地图和实现,但找到了一种基于树图创建排序多重地图的方法。
然后我使用了一个逆序比较器,它允许我根据需要对值进行排序。感谢其他人,他们对信息发表了评论,因为它非常有帮助。
我最终使用的代码如下:
Multimap<Integer, Entry> sortedMap = Multimaps.newListMultimap(new TreeMap<>(Collections.reverseOrder()), Lists::newArrayList);