Access values of hashmap

Possible Duplicate:
How do I iterate over each Entry in a Map?

I am having a MAP, Map<String, Records> map = new HashMap<String, Records> ();

public class Records 
{
    String countryName;
    long numberOfDays;

    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public long getNumberOfDays() {
        return numberOfDays;
    }
    public void setNumberOfDays(long numberOfDays) {
        this.numberOfDays = numberOfDays;
    }

    public Records(long days,String cName)
    {
        numberOfDays=days;
        countryName=cName;
    }

    public Records()
    {
        this.countryName=countryName;
        this.numberOfDays=numberOfDays;
    }

I have implemented the methods for map, now please tell me How do I access all the values that are present in the hashmap. I need to show them on UI in android ?


You can use Map#entrySet method, if you want to access the keys and values parallely from your HashMap : -

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

//Populate HashMap

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

Also, you can override toString method in your Record class, to get String Representation of your instances when you print them in for-each loop.

UPDATE : -

If you want to sort your Map on the basis of key in alphabetical order, you can convert your Map to TreeMap . It will automatically put entries sorted by keys: -

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

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

    }

For more detailed explanation, see this post: - how to sort Map values by key in Java


你可以通过使用for循环来完成

Set keys = map.keySet();   // It will return you all the keys in Map in the form of the Set


for (Iterator i = keys.iterator(); i.hasNext();) 
{

      String key = (String) i.next();

      Records value = (Records) map.get(key); // Here is an Individual Record in your HashMap
}

map.values()为您提供了一个包含HashMap中所有值的Collection

链接地址: http://www.djcxy.com/p/23968.html

上一篇: 迭代hashmap

下一篇: 访问hashmap的值