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

pal*_*laa 5 java collections

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

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

Joã*_*lva 18

您可以使用a 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]
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用Multimapguava,如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]
Run Code Online (Sandbox Code Playgroud)

  • 多图相对于该解决方案的优势在于,您可以将单个元素添加到任何键,而无需检查那里是否已经存在列表。有时这无关紧要,但通常确实如此。 (2认同)

Ber*_*ann 8

你可以使用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". 
Run Code Online (Sandbox Code Playgroud)

  • 通用版本:http://guava-libraries.googlecode.com/svn/tags/release02/javadoc/com/google/common/collect/Multimap.html (5认同)