有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在一个映射中具有多个值的键?

我有一张这样的地图

Map map=new HashMap();//HashMap key random order.
map.put("a",10);
map.put("a",20);
map.put("a",30);
map.put("b",10);

System.out.println("There are "+map.size()+" elements in the map.");
System.out.println("Content of Map are...");
Set s=map.entrySet();
Iterator itr=s.iterator();
while(itr.hasNext())
{
    Map.Entry m=(Map.Entry)itr.next();
    System.out.println(m.getKey()+"\t"+m.getValue()+"\t"+ m.hashCode());
}

上述程序的输出为

There are 2 elements in the map.
Content of Map are...
b   10  104
a   30  127

现在我希望键a应该有多个值,比如

a 10
a 20
a 30

因此,我应该获得a关联的所有值。请建议我如何实现相同的目标。通过嵌套集合,我希望键“a”具有所有这三个值


共 (6) 个答案

  1. # 1 楼答案

    要使用Java标准库实现您想要的功能,我将使用如下映射:

    Map<String, Collection<Integer>> multiValueMap = new HashMap<String, Collection<Integer>>();
    

    然后可以添加值:

    multiValueMap.put("a", new ArrayList<Integer>());
    multiValueMap.get("a").add(new Integer(10));
    multiValueMap.get("a").add(new Integer(20));
    multiValueMap.get("a").add(new Integer(30));
    

    如果这个结果对你来说不舒服,考虑把这个行为包在一个专用的类中,或者使用第三方解决方案,正如其他人在这里所建议的(Guava Multimap)。p>

  2. # 2 楼答案

    将值类型为的映射用作值列表。。例如,在地图中,当添加一个条目时,您将把key作为“a”,并且您必须将其值添加为整数列表,包含所有必需的值,如1,2,3,4

  3. # 3 楼答案

    ArrayList实例放入值部分

    void addValue(Map map, Object key, Object value) {
        Object obj = map.get(key);
        List list;
        if (obj == null) {  
            list = new ArrayList<Object>();  
        } else {
            list = ((ArrayList) obj);
        }
        list.add(value);
        map.put(key, list);
    }
    

    有关更多信息,请查看this

  4. # 4 楼答案

    您不应该忽略泛型参数。你所拥有的是

    Map<String, Integer> map = new HashMap<>();
    

    如果您想自己编写解决方案,您需要

    Map<String, List<Integer>> map = new HashMap<>();
    

    无论如何,首选的方法是使用Guava Multimap

  5. # 5 楼答案

    对于具有相同键的条目的映射,使用get()没有意义。但只要您使用iterator()entrySet(),这应该可以:

    class HashMap<String, String> {
    
      Set<Entry<String, String>> entries;
      @Override
      public Set<Entry<String, String>> entrySet() {
        return entries;
      }
    
      @Override
      public int size() {
        return entries.size();
      }
    
      public String put(String key, String value) {
        if (entries == null) {
          entries = new AbstractSet<Entry<String, String>>() {
    
            ArrayList<Entry<String, String>> list = new ArrayList<>();
            @Override
            public Iterator<Entry<String, String>> iterator() {
              return list.iterator();
            }
    
            @Override
            public int size() {
              return list.size();
            }
    
            @Override
            public boolean add(Entry<String, String> stringStringEntry) {
              return list.add(stringStringEntry);
            }
          };
        }
        StatusHandler.MyEntry entry = new StatusHandler.MyEntry();
        entry.setKey(key);
        entry.setValue(value);
        entries.add(entry);
        return value;
      }
    };
    

    TL;苏博士,它有什么用处?这源于对java api进行重新挖掘以接受基于表单参数的复杂查询的黑客攻击:

    https://stackoverflow.com/a/18358659/848072

    https://github.com/albfan/RedmineJavaCLI/commit/2bc51901f2f8252525a2d2258593082979ba7122

  6. # 6 楼答案

    你退房了吗

    A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

    如果您确实想使用标准集合(如下所示),则必须为每个键存储一个集合,例如

    map = new HashMap<String, Collection<Integer>>();
    

    请注意,第一次输入新键时,必须在添加第一个值之前创建新集合(ListSet等)