11

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 ?

1
  • What error you come across? You should able to get the record by the key you assigned for the record or you can iterate it by foreach loop. Commented Oct 22, 2012 at 8:50

4 Answers 4

6

You can do it by using for loop

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
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Is there any way by which I can sort keys are per alphabetical order ?
@onkar. You can use TreeMap for that case. See this post: - stackoverflow.com/questions/922528/…
0

If you are having HashMap ready with data, then you just need to iterate over HashMap keys. Just implement an iteration and fetch data one by one.

Check this: Iterate through a HashMap

Comments

0

map.values() gives you a Collection with all the values in your HashMap.

Comments