访问hashmap的值

6 java android

可能重复:
如何迭代Map中的每个条目?

我有一个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;
    }
Run Code Online (Sandbox Code Playgroud)

我已经实现了map的方法,现在请告诉我如何访问hashmap中存在的所有值.我需要在Android的UI上显示它们吗?

M.M*_*sin 6

您可以使用 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
}
Run Code Online (Sandbox Code Playgroud)


Roh*_*ain 3

如果您想从以下位置Map#entrySet访问keys并并行,您可以使用方法:-valuesHashMap

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());
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以重写类toString中的方法,以便在循环打印它们时Record获取字符串表示形式。instancesfor-each

更新: -

如果您想按字母顺序对您的内容进行排序Mapkey您可以将您的内容转换MapTreeMap. 它将自动将条目按键排序:-

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

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

    }
Run Code Online (Sandbox Code Playgroud)

更详细的解释,请参阅这篇文章: - how to sort Map value by key in Java