如何从哈希映射中添加的java中的列表中获取值

时间:2014-10-31 06:31:21

标签: java list collections

我对以下代码有疑问:

public static void main(String[] args) {
    HashMap<String,String> hMap = new HashMap<String,String>();
    System.out.println("Size of HashMap : " + hMap.size());
    hMap.put("1", "One");
    hMap.put("2", "Two");
    hMap.put("3", "Three");
    System.out.println("Size of HashMap after addition : " + hMap.size());
    // remove one element from HashMap
    ArrayList<HashMap<String, String>> list;
    list = new ArrayList<HashMap<String, String>>();
    list.add(hMap);
    System.out.println(""+hMap.get(1));
    System.out.println(""+list.size());
    //if(list.size()<1)
    System.out.println(""+list.get(0));
}

输出

Size of HashMap : 0
Size of HashMap after addition : 3
null
1
{3=Three, 2=Two, 1=One}

Myquestion

如何从列表中获取每个值?

2 个答案:

答案 0 :(得分:1)

  

如何从列表中获取每个值?

只需遍历列表并获取每个值

for (HashMap<String, String> currentmap : list) { // foreach loop   
      System.out.println(currentmap);// do something with currentmap
    for (Map.Entry<String, String> entry : currentmap.entrySet()) {
      System.out.println(entry.getValue()); //each value of map
   }
}

答案 1 :(得分:1)

您的列表中有一个对象是Map。如果您希望获得该单个Map的值,只需迭代它们:

for (String value : list.get(0).values()) {
    System.out.println(value);
}

如果您的列表有多个条目,则可以使用嵌套循环:

for (Map<String,String> map : list)
    for (String value : map.values()) {
        System.out.println(value);
    }