Access values of hashmap

android, java

Solution

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

Problem

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 ?

Original source

Related problems