我有一个MultiMap,需要使用列表中的一个值来获得MultiMap的EntrySet的最佳方法。现在,我正在迭代整个map的条目集,并检查列表的值是否包含我需要的值。这对地图上的有限数量的输入有效,但现在它变成了800ms -1秒的工作,这不会减少它。感谢你在高级课程中的帮助。
示例:
public static void main(String[] args) {
MultiMap multi = new MultiHashMap();
multi.put("Key1", new ArrayList<String>(Arrays.asList(new String[] { "Value1", "Value2", "Value3" })));
}我希望能够通过仅输入Value3和Value1作为参数来获取Value1、Value2和Value2
此外,如果有任何帮助,这是在读取数据源之后从缓存中获取的
发布于 2011-10-19 09:57:29
编辑以允许同时测试一组值
现在问题已经被澄清了,再次编辑
此实现避免了显式循环,并使用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
我很想知道它的效率有多低。
发布于 2011-10-19 09:41:05
你有没有尝试过Apache Common的Collections?他们有一个可能对您有帮助的multimap实现,特别是containsValue方法。
假设值中没有重复的元素,您可以使用一个集合来保存多个值,并加快搜索速度。这只是一个(未经测试的)想法,就像这样:
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;
}https://stackoverflow.com/questions/7815614
复制相似问题