【发布时间】:2011-07-27 20:36:23
【问题描述】:
什么类型的 java 集合会为同一个键返回多个值?
例如,我想为键 300 返回 301,302,303。
【问题讨论】:
标签: java collections
什么类型的 java 集合会为同一个键返回多个值?
例如,我想为键 300 返回 301,302,303。
【问题讨论】:
标签: java collections
您可以使用List 作为Map 的值:
List<Integer> list = new ArrayList<Integer>();
list.add(301);
list.add(302);
list.add(303);
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
map.put(300, list);
map.get(300); // [301,302,303]
或者,您可以使用来自 Guava 的 Multimap,正如 biziclop 所建议的那样,它具有更简洁的语法和许多其他非常有用的实用方法:
Multimap<Integer, Integer> map = HashMultimap.create();
map.put(300, 301);
map.put(300, 302);
map.put(300, 303);
Collection<Integer> list = map.get(300); // [301, 302, 303]
【讨论】:
Multimap 很好地简化了这一点,但我倾向于使用 Map 的概念,put(key, value) 只是简单地覆盖键的现有值。
您可以使用 Multimap,它在 Apache 许可下。
见this link。为后代:
org.apache.commons.collections
Interface MultiMap
All Superinterfaces:
java.util.Map
All Known Implementing Classes:
MultiHashMap, MultiValueMap
public interface MultiMap
extends java.util.Map
Defines a map that holds a collection of values against each key.
A MultiMap is a Map with slightly different semantics. Putting a value into the map will add the value to a Collection at that key. Getting a value will return a Collection, holding all the values put to that key.
For example:
MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);
coll will be a collection containing "A", "B", "C".
【讨论】:
正如上面评论中提到的,始终存在 Guava Multimap
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html
Apache Commons Collections 4 有通用版的 MultiMap http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiMap.html
JAX-RS 指定了一个由所有 JAX-RS 提供者实现的 MultivaluedMap 接口。 如果您的用例在 JAX-RS REST 服务/客户端的上下文中,则可以选择使用它们的实现而不引入另一个依赖项。
javax.ws.rs.core.MultivaluedMap(每个 JAX RS Provider 都有自己的实现)
【讨论】: