什么java集合为同一个键提供多个值
什么类型的java集合为同一个键返回多个值?
例如,我想为密钥300返回301,302,303。
您可以使用List
作为Map
的值:
List list = new ArrayList (); list.add(301); list.add(302); list.add(303); Map> map = new HashMap>(); map.put(300, list); map.get(300); // [301,302,303]
或者,您可以使用来自Guava的Multimap
,如biziclop所建议的,它具有更清晰的语法,以及许多其他非常有用的实用方法:
Multimap map = HashMultimap.create(); map.put(300, 301); map.put(300, 302); map.put(300, 303); Collection list = map.get(300); // [301, 302, 303]
你可以使用Multimap,它是在Apache许可下。
看到这个链接 。 后人:
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都有自己的实现)