【问题标题】:what java collection that provides multiple values for the same key为同一个键提供多个值的 java 集合
【发布时间】:2011-07-27 20:36:23
【问题描述】:

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

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

【问题讨论】:

    标签: java collections


    【解决方案1】:

    您可以使用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 优于此解决方案的优点是您可以将单个元素添加到任何键,而无需检查那里是否已经存在列表。有时这无关紧要,但通常确实如此。
    • 确实,有时我确实厌倦了编写相同的旧代码来验证是否已经存在给定键的集合,如果不存在则创建一个新的。 Guava 的 Multimap 很好地简化了这一点,但我倾向于使用 Map 的概念,put(key, value) 只是简单地覆盖键的现有值。
    • 这一切都取决于你真正需要什么,而且这个问题太简洁了,无法决定。
    【解决方案2】:

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

    【讨论】:

    • biziclop 是的不错的建议,您应该将此添加为另一个答案,这样您就可以获得积分和免费啤酒
    • 我不太介意这些点。但是那种免费的啤酒听起来很诱人。 :)
    • 使用 Multimap 与上面建议的值是列表的映射相比有什么优势?
    • 它的语法更简单,并且有很多有用的实用方法。但是,在内部,它的实现方式几乎相同。
    【解决方案3】:
    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 提供者实现的 MultivaluedMap 接口。 如果您的用例在 JAX-RS REST 服务/客户端的上下文中,则可以选择使用它们的实现而不引入另一个依赖项。

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

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 2018-09-08
      • 2015-07-09
      相关资源
      最近更新 更多