【问题标题】:Access values of hashmap [duplicate]访问哈希图的值 [重复]
【发布时间】:2012-10-12 01:07:56
【问题描述】:

可能重复:
How do I iterate over each Entry in 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;
    }

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

【问题讨论】:

  • 你遇到了什么错误?您应该能够通过为记录分配的键获取记录,或者您可以通过 foreach 循环对其进行迭代。

标签: java android


【解决方案1】:

map.values() 为您提供 Collection,其中包含您的 HashMap 中的所有值。

【讨论】:

    【解决方案2】:

    如果您已经准备好 HashMap 的数据,那么您只需要遍历 HashMap 键。只需实现一个迭代并一个一个地获取数据。

    检查这个:Iterate through a HashMap

    【讨论】:

      【解决方案3】:

      如果您想从您的HashMap 并行访问keysvalues,您可以使用Map#entrySet 方法:-

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

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

      更新:-

      如果您想根据key 按字母顺序对Map 进行排序,您可以将Map 转换为TreeMap。它会自动将条目按键排序:-

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

      更详细的解释可以看这个帖子:-how to sort Map values by key in Java

      【讨论】:

      【解决方案4】:

      你可以使用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
      }
      

      【讨论】:

        猜你喜欢
        • 2020-12-21
        • 2013-06-06
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        • 2013-03-22
        • 1970-01-01
        • 1970-01-01
        • 2012-12-30
        相关资源
        最近更新 更多