Iterating over hashmap

Possible Duplicate:
How do I iterate over each Entry in a Map?
How can I iterate over a map of <String, POJO>?

I've written the following piece of code and am stuck on iterating over the hashmap.

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

In this code, there are six elments inside the map, now in the main method how can I iterate over the map and get the total count?

Thank you.


Your question is asked - and answered - here:

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

Take a look at the JavaDoc. You're looking for HashMap.size() for the total count and HashMap.values() for all of the values in the map, or HashMap.entries() for each pair of key and value.


The 'Map' data structure isn't a Collection object but Sets are.

The most common method to iterate over a Map is using the underlying .entrySet method.

// 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() ) );
}

If are interested in finding the total number of Map nodes, use the .size() method.

EDIT:

Since you want the total size of each list stored within the map, you could do something like this.

Iterator iterator = names.entrySet().iterator
int count = 0;

while( iterator.hasNext() ){
     Entry entry = iterator.next()
     count += entry.getValue().size()
}
链接地址: http://www.djcxy.com/p/23970.html

上一篇: 我如何分别从HashMap获取对象?

下一篇: 迭代hashmap