gpt4 book ai didi

java - 获取 MultiMap 中的 EntrySet

转载 作者:行者123 更新时间:2023-12-01 05:38:12 24 4
gpt4 key购买 nike

我有一个 MultiMap,并且需要使用列表中的值之一获取 MultiMap 的 EntrySet 的最佳方法。现在,我正在迭代整个映射的条目集并检查列表的值是否包含我需要的值。这适用于 map 上有限数量的输入,但现在变成了 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

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

最佳答案

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

[既然问题已经澄清,再次编辑]

此实现避免了显式循环,并使用 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]

我很想知道它的效率有多低。

关于java - 获取 MultiMap 中的 EntrySet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7815614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com