【问题标题】:How to convert List to a HashMap如何将 List 转换为 HashMap
【发布时间】:2011-05-11 17:29:14
【问题描述】:

如何转换:

Map<String, Integer> itemsBought

这样我就可以将它添加到 ArrayList 中,如下所示:

public void add(String prd, int qty){
        orderList.add(new Order(prd, qty));
}

除此之外还有其他解决方案吗:

hashMap.keySet().toArray(); 
hashMap.values().toArray(); 

提前谢谢你。

【问题讨论】:

    标签: java hashmap type-conversion


    【解决方案1】:
    for (Entry<String, Integer> entry : itemsBought.entrySet()) {
        orderList.add(new Order(entry.getKey(), entry.getValue()));
    }
    

    【讨论】:

      【解决方案2】:
      for (String product : itemsBought.keySet()) {
          int quantity = itemsBought.get(product);
          orderList.add(new Order(product, quantity));
      }
      

      我更喜欢可读性(虽然不多)

      【讨论】:

      • L 不管实现如何,Tarlog 的回答清楚地表明,您必须迭代集合才能填充ArrayList。话虽如此,我认为这个答案没有任何价值。
      • 此解决方案对每个键进行映射查找(这可能是 O(n) 最坏的情况,具体取决于实现,查看 O(2n))。第一个解决方案,再次依赖于实现,可能简单地遍历 O(n) 中的所有条目。不过,对于微不足道的地图大小,这完全无关紧要。
      猜你喜欢
      • 2015-09-28
      • 1970-01-01
      • 2011-07-25
      • 2016-06-27
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      相关资源
      最近更新 更多