标签:style blog http os io 使用 java ar for
1.最常规的一种遍历方法,最常规就是最常用的,虽然不复杂,但很重要,这是我们最熟悉的,就不多说了!!
public static void work(Map<String, Student> map) {
Collection<Student> c = map.values();
Iterator it = c.iterator();
for (; it.hasNext();) {
System.out.println(it.next());
}
}
2.利用keyset进行遍历,它的优点在于可以根据你所想要的key值得到你想要的 values,更具灵活性!!
public static void workByKeySet(Map<String, Student> map) {
Set<String> key = map.keySet();
for (Iterator it = key.iterator(); it.hasNext();) {
String s = (String) it.next();
System.out.println(map.get(s));
}
}
3.比较复杂的一种遍历在这里,呵呵~~他很暴力哦,它的灵活性太强了,想得到什么就能得到什么~~
public static void workByEntry(Map<String, Student> map) {
Set<Map.Entry<String, Student>> set = map.entrySet();
for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it.hasNext();) {
Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next();
System.out.println(entry.getKey() + "--->" + entry.getValue());
}
}
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
转载自http://www.cnblogs.com/kristain/articles/2033566.html
标签:style blog http os io 使用 java ar for
原文地址:http://www.cnblogs.com/joycelishanhe/p/3949311.html