我正在尝试创建 id 号的键和集合的值,但我还需要编写对那些陷入值的集合进行迭代的通用方法(需要 Iterable,因此我尝试使用集合)。在属于 Map 对象一部分的某些泛型值上实现迭代器的有效方法是什么?
最佳答案
您所描述的,a Map<X, Set<Y>>
,通常被称为“基于集合的 MultiMap”。
这种 Map 的一个流行实现是 Google Guava
索要这样一张 map values()
将返回一个包含 Y
的所有值的集合(并非所有 Set<Y>
实例)。
人们可以使用基本的映射“手动”实现这样的集合,但是事实证明,要真正针对所有用例实现正确的实现并保留 Java 集合框架语义是非常困难的。因此,使用库的实现通常是最佳选择。
另一种选择是使用 Stream API (Java8),以及诸如 groupBy
之类的收集器。构建 Map 实例,以及其他流操作,以便在您想要迭代值时“展平” map 的值(例如,请参阅 Flattening a collection)。
下面是 SetMultiMap 代码示例
public static void main(String[] args) {
Multimap<Integer, String> multiMap = HashMultimap.create();
multiMap.put(0, "key0_value0");
// Twice the same value for the same key, the Set<String> will "ignore" this
multiMap.put(0, "key0_value0");
multiMap.put(1, "key1_value0");
multiMap.put(1, "key1_value1");
System.out.println("Values for key 0");
System.out.println("----------------");
System.out.println(multiMap.get(0));
System.out.println("\r\nValues for key 1");
System.out.println("----------------");
System.out.println(multiMap.get(1));
System.out.println("\r\nAll values");
System.out.println("------------");
System.out.println(multiMap.values());
// Entries are all Integer/String associations
Collection<Entry<Integer, String>> entries = multiMap.entries();
System.out.println("\r\nNumber of entries : " + entries.size());
// We can build a standard Java Map out of the Multimap
Map<Integer, Collection<String>> realJavaMap = multiMap.asMap();
// The map's values are actually guaranteed to be Sets
System.out.println("Multimap as Map, values implement Set : " + Set.class.isAssignableFrom(realJavaMap.values().iterator().next().getClass()));
// The java Map is a live view of the multimap
realJavaMap.get(0).add("key0_value1"); // Actions on realJavaMap will update multimap
System.out.println("\r\nValues for key 0");
System.out.println("----------------");
System.out.println(multiMap.get(0));
}
该程序输出:
Values for key 0
----------------
[key0_value0]
Values for key 1
----------------
[key1_value1, key1_value0]
All values
------------
[key0_value0, key1_value1, key1_value0]
Number of entries : 3
Multimap as Map, value class is set : true
Values for key 0
----------------
[key0_value1, key0_value0]
关于Java map 要设置吗?有没有办法实现预先存在的java库以允许包含Sets作为值的Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28851109/