JAVA使用列表迭代Hashmap

时间:2014-03-28 19:25:45

标签: java hashmap

我需要遍历hashmap并获取键值,该值应该是一个字符串,并且该键中的所有值都是具有字符串的字符串列表?

Psuedo代码

static HashMap<String, List<String>> vertices  = new HashMap<String, List<String>>();
for (int i = 0; i < vertices.size(); i++)
{

       String key = vertices.getKey at first postions;

    for (int x = 0; x < size of sublist of the particular key; x++)
       {
              String value = vertices key sublist.get value of sublist at (i);

          }
}

2 个答案:

答案 0 :(得分:1)

尝试vertices.keySet();

它在地图中提供了一组所有键。在下面的for循环中使用它

for (String key : vertices.keySet()) {
   for (String value : vertices.get(key)) { 
       //do stuff
   }
}

答案 1 :(得分:1)

您无法直接迭代HashMap,因为HashMap中没有值的数字索引。在类型key的情况下,使用String值。因此,这些值没有特定的顺序。但是,如果需要,可以使用vertices.entrySet()构建一组条目并对其进行迭代。

for (Entry<String, List<String>> item : vertices.entrySet()) {
    System.out.println("Vertex: " + item);
    for (String subitem : item.getValue()) {
        System.out.println(subitem);
    }
}
相关问题