在MultiMap中获取EntrySet

时间:2011-10-19 01:31:12

标签: java multimap

我有一个MultiMap,需要使用列表中的一个值来获取MultiMap的EntrySet的最佳方法。现在,我正在迭代整个地图的入口集,并检查列表的值是否包含我需要的值。这适用于地图上有限数量的输入,但它现在变成800毫秒 - 1秒钟的工作,它不会削减它。感谢先进的帮助。

示例:

public static void main(String[] args) {
        MultiMap multi = new MultiHashMap();
        multi.put("Key1", new ArrayList<String>(Arrays.asList(new String[] { "Value1", "Value2", "Value3" })));
}

我希望能够通过仅输入Value1和Value2作为参数来获取Key1,Value1,Value2和Value3

此外,如果有任何帮助,这是在读取数据源后从缓存中

2 个答案:

答案 0 :(得分:0)

您是否尝试过Apache Common的Collections?他们有multimap实施可能对您有所帮助,尤其是containsValue方法。

假设值中没有重复元素,您可以使用Set来保存多值并加快搜索速度。只是一个(未经测试的)想法,如下所示:

public static <K, V> Map.Entry<K, Set<V>> getEntry(Map<K,Set<V>> map, Set<V> vals) {
    for (Map.Entry<K, Set<V>> entry : map.entrySet()) {
        boolean found = true;
        for (V val : vals) {
            if (!entry.getValue().contains(val)) {
                found = false;
                break;
            }
        }
        if (found)
            return entry;
    }
    return null;
}

答案 1 :(得分:0)

[编辑允许同时测试一组值]

[现在再次编辑,问题已经澄清]

此实现避免了显式循环,并使用Guava扩展以更具功能性的方式编写:

import java.util.Collection;
import java.util.Map.Entry;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;

public class TestIt {

    public static Iterable<Entry<Integer, String>> getEntrySetsForValues(
            Multimap<Integer, String> fromMap, final Collection<String> values) {
        return Iterables.filter(fromMap.entries(),
                new Predicate<Entry<Integer, String>>() {
                    @Override
                    public boolean apply(Entry<Integer, String> arg0) {
                        return values.contains(arg0.getValue());
                    }
                });
    }
}

测试程序:

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;

public class Test {

    static Multimap<Integer, String> x = HashMultimap.create();

    public static void main(String[] args) {
        x.put(1, "a");
        x.put(1, "b");
        x.put(2, "d");
        x.put(3, "e");
        x.put(3, "f");
        x.put(4, "a");
        x.put(5, "b");
        x.put(5, "c");

        System.out.println(TestIt.getEntrySetsForValues(x,
                Sets.newHashSet("a", "c")));
    }
}

输出:

[1 = a,4 = a,5 = c]

我很想知道它是多么低效。