按值数对Guava Multimap进行排序 [英] Sort Guava Multimap by number of values

查看:1652
本文介绍了按值数对Guava Multimap进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个Guava Multimap,我如何根据给定密钥的值数对这些条目进行排序?

If I have a Guava Multimap, how would I sort the entries based on the number of values for the given key?

例如:

Multimap<String, String> multiMap = ArrayListMultimap.create();
multiMap.put("foo", "1");
multiMap.put("bar", "2");
multiMap.put("bar", "3");
multiMap.put("bar", "99");

鉴于此,在迭代multiMap时,我如何才能获得bar条目(因为bar有3个值,而foo只有1个?

Given this, when iterating over multiMap, how would I get the "bar" entries to come first (since "bar" has 3 values vs. only 1 for "foo")?

推荐答案

提取列表中的条目,然后对列表进行排序:

Extract the entries in a list, then sort the list :

List<Map.Entry<String, String>> entries = new ArrayList<Map.Entry<String, String>>(map.entries());
Collections.sort(entries, new Comparator<Map.Entry<String, String>>() {
    @Override
    public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
        return Ints.compare(map.get(e2.getKey()).size(), map.get(e1.getKey()).size());
    }
});

然后迭代条目。

编辑:

如果您想要的实际上是迭代内部地图的条目(条目< String,Collection< String>> ),然后执行以下操作:

If what you want is in fact iterate over the entries of the inner map (Entry<String, Collection<String>>), then do the following :

List<Map.Entry<String, Collection<String>>> entries = 
    new ArrayList<Map.Entry<String, Collection<String>>>(map.asMap().entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Collection<String>>>() {
    @Override
    public int compare(Map.Entry<String, Collection<String>> e1, 
                       Map.Entry<String, Collection<String>> e2) {
        return Ints.compare(e2.getValue().size(), e1.getValue().size());
    }
});

// and now iterate
for (Map.Entry<String, Collection<String>> entry : entries) {
    System.out.println("Key = " + entry.getKey());
    for (String value : entry.getValue()) {
        System.out.println("    Value = " + value);
    }
}

这篇关于按值数对Guava Multimap进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆