【问题标题】:Regarding map different implementation [closed]关于地图不同的实现[关闭]
【发布时间】:2012-11-23 09:24:23
【问题描述】:

我有以下地图..

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));

         System.out.println("There are "+multiValueMap.size()+" elements in the map.");
         System.out.println("Content of multiValueMap are...");
         Set s=multiValueMap.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 1 elements in the map.
Content of multiValueMap are...
a   [10, 20, 30]    39954

请告知是否可以通过 Guava Multimap 实现同样的事情,如果那样,请告知..!!

【问题讨论】:

  • 您有实际问题吗?

标签: java collections map guava


【解决方案1】:
 Multimap<String, Integer> multimap = ArrayListMultimap.create();
 multimap.putAll("a", ImmutableList.of(10, 20, 30));
 System.out.println("There are " + multimap.keySet().size() +
     " elements in the map.");
 System.out.println("Content of multimap are...");
 for (Map.Entry<String, Collection<Integer>> asMapEntry :
     multimap.asMap().entrySet()) {
   System.out.printf("%s\t%s\t%s%n", asMapEntry.getKey(), asMapEntry.getValue(),
       asMapEntry.hashCode());
 }

【讨论】:

    【解决方案2】:

    要获得MultiMap键的数量,可以使用Multimap.keySet().size()

    你也可以迭代这个集合并使用Multimap.get(key) 获取附加到此键的所有值的集合。

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 2018-11-24
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      相关资源
      最近更新 更多