【问题标题】:How to sort Guava MultiMap by count of values for each key如何按每个键的值计数对 Guava MultiMap 进行排序
【发布时间】:2014-01-28 07:38:34
【问题描述】:

我已经看到了这个问题和答案here,但我的用例是在创建过程中进行的。

我可以创建一个这样的多图:

ImmutableListMultimap<Foo, Bar> indexMultiMap = Multimaps.index(barCollection, new Function<Bar, Foo>() {
     @Override
     public Foo apply(Bar bar) {
        //some works
        return Foo;
     }
  });

我知道 Foo 元素将是唯一的,并且我想按此地图中每个 Foo 元素大小(每个 Foo 元素的 Bar 集合的每个 Foo 元素大小)的频率对这个地图进行排序,降序。

1) 我怎样才能通过一次迭代来做到这一点?就像在将此集合索引到 MultiMap 时这样做

2) 如果不是这样,那么获得它的有效方法是什么?

我的目标是,当我迭代这张地图时,我希望看到第一个键有更多的值,比如

Foo -> 3(此键对应的条形集合大小)

Foo -> 3

Foo -> 2

Foo -> 1

Foo -> 1

【问题讨论】:

  • 您能否也给我们示例输入代码?
  • @Xaerxess 输入只是一个 Collection ?你还想看什么?

标签: java sorting guava multimap


【解决方案1】:

来自Multimaps.index()的javadoc;

“在返回的多重映射中,键按照它们第一次遇到的顺序出现......”

如果以“模拟”隐式排序行为的方式对集合进行排序,则将以您想要的顺序创建多图。例如:

SortedMultiset preSorted = TreeMultiset.create(fooComparator);

然后使用上述预排序集合馈送Multimaps.index()

【讨论】:

    【解决方案2】:

    正如@px5x2 所说。当您调用Multimaps.index() 时,键会按照它们第一次遇到的顺序出现。因此,首先对您的收藏进行排序。在此处使用 Guava Multimaps.index() 示例,稍作修改。

    ImmutableSet<String> digits = ImmutableSet.of("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine");
    Function<String, Integer> lengthFunction = new Function<String, Integer>(){
        public Integer apply(String input) {
            return input.length();
        }
    };
    ImmutableMultimap<Integer, String> sortedOnLength = Multimaps.index(
        Ordering.natural().onResultOf(lengthFunction).sortedCopy(digits), 
        lengthFunction
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 2011-07-26
      • 2013-09-14
      • 1970-01-01
      相关资源
      最近更新 更多