什么java集合为同一个键提供多个值

时间:2011-07-27 20:36:23

标签: java collections

哪种类型的java集合为同一个键返回多个值?

例如,我想为密钥300返回301,302,303。

3 个答案:

答案 0 :(得分:17)

您可以使用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]

答案 1 :(得分:8)

您可以使用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". 

答案 2 :(得分:1)

  1. 正如上面评论中提到的那样,总有Guava Multimap
    http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html

  2. Apache Commons Collections 4具有MultiMap的通用版本http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiMap.html

  3. JAX-RS指定了一个由所有JAX-RS提供程序实现的多值地图接口。 如果您的用例位于JAX-RS REST服务/客户端的上下文中,则可以选择在不引入其他依赖项的情况下使用其实现。

    javax.ws.rs.core.MultivaluedMap(每个JAX RS Provider都有自己的实现)