【问题标题】:Iterating over hashmap [duplicate]迭代哈希图[重复]
【发布时间】:2012-12-27 09:50:28
【问题描述】:

可能重复:
How do I iterate over each Entry in a Map?
How can I iterate over a map of <String, POJO>?

我已经编写了以下代码,并且一直在迭代哈希图。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

class demo
{
    public static void main(String v[]) {
        ArrayList<String> contactIds = new ArrayList<String>();
        contactIds.add("2");
        contactIds.add("3");

        HashMap names = new HashMap();
        names =  getNames(contactIds);

        // I want to get the total size of the hashmap  - names
        // for ex now there are 6 elements inside hashmap.
        // How can I get that count?

    }


    private static HashMap getNames(ArrayList contactIds) {
        HashMap names = new HashMap();
        String params = null;
        List<String> list = new ArrayList<String>();
        for(int i=0; i<contactIds.size();i++) {
            params = contactIds.get(i).toString();

            list.add(0,"aer-1");
            list.add(1,"aer-2");
            list.add(2,"aer-3");

            names.put(params,list) ;
         }

        return names;
    }
}

在这段代码中,地图中有六个元素,现在在 main 方法中,我如何遍历地图并获得总数?

谢谢。

【问题讨论】:

    标签: java collections hashmap


    【解决方案1】:

    'Map' 数据结构不是 Collection 对象,但 Sets 是。

    迭代 Map 的最常用方法是使用底层的 .entrySet 方法。

    // For each loop
    for ( Entry<String, String> entry : names ) {
        System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
    }
    
    // Iterator
    Iterator iterator = names.entrySet().iterator
    while( iterator.hasNext() ){
         Entry entry = iterator.next()
         System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
    }
    

    如果有兴趣查找 Map 节点的总数,请使用 .size() 方法。

    编辑:

    由于您希望将每个列表的总大小存储在地图中,您可以这样做。

    Iterator iterator = names.entrySet().iterator
    int count = 0;
    
    while( iterator.hasNext() ){
         Entry entry = iterator.next()
         count += entry.getValue().size()
    }
    

    【讨论】:

    • 但是我怎样才能得到哈希图中元素的总数。例如,为键 1 和键 2 添加了 3 个元素。现在我想要总大小,即 6。有可能吗?
    • 没有名为size()的方法
    • 地图中的值使用什么数据结构?在您的代码中,它看起来像一个 ArrayList,它是一个集合数据结构,因此它应该有一个 .size() 方法。
    【解决方案2】:

    您的问题在此处被问及 - 并得到回答:

    How to efficiently iterate over each Entry in a Map?

    for (Map.Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "/" + entry.getValue());
    }
    

    【讨论】:

    • 但是我怎样才能得到哈希图中元素的总数。例如,为键 1 和键 2 添加了 3 个元素。现在我想要总大小,即 6。有可能吗?
    【解决方案3】:

    看看JavaDoc。您正在寻找 HashMap.size() 来获取总计数,HashMap.values() 来获取映射中的所有值,或者 HashMap.entries() 来获取每对键和值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2011-02-28
      • 2014-12-15
      • 2017-09-02
      相关资源
      最近更新 更多