您的位置:首页 > 编程语言 > Java开发

JAVA Map的三种遍历方式

2014-05-30 17:43 369 查看
原文:http://chevy.iteye.com/blog/1446786

第一种:把值放到一个集合里,然后遍历集合

public class TraversalMap1 {
private static final Map<Integer, String> map;

static {
map = new HashMap<Integer, String>();
map.put(1, "value1");
map.put(2, "value2");
map.put(3, "value3");
map.put(4, "value4");
}

public static void main(String[] args) {
Collection<String> c = map.values();
Iterator<String> i = c.iterator();
for (; i.hasNext();) {
System.out.println(i.next());// 遍历出map内的所有value
}

}
}


第二种:利用keyset进行遍历。

public class TraversalMap2 {
private static final Map<Integer, String> map;

static {
map = new HashMap<Integer, String>();
map.put(1, "value1");
map.put(2, "value2");
map.put(3, "value3");
map.put(4, "value4");
}

public static void main(String[] args) {
Set<Integer> set = map.keySet();
Iterator<Integer> i = set.iterator();
for (; i.hasNext();) {
System.out.println(i.next());// 遍历出map内的所有key
}

}
}

第三种:利用entrySet进行遍历。

public class TraversalMap3 {
private static final Map<Integer, String> map;

static {
map = new HashMap<Integer, String>();
map.put(1, "value1");
map.put(2, "value2");
map.put(3, "value3");
map.put(4, "value4");
}

public static void main(String[] args) {
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("the map key is : " + entry.getKey() + " || the value is : "
+ entry.getValue());// 显示出map的key和value
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: