一丶获取集合中所有key-value的key组成的Set集合后进行遍历:
1.加强for循环:
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<String, Integer>();
scores.put("Tom", 91);
scores.put("Jim", 89);
scores.put("Jack", 95);
Set<String> names = scores.keySet();
for(String key : names) {
System.out.println(key);
}//换行依次输出"Tom","Jim","Jack"
}
}
不足:该方法只能遍历Map集合的key值.
2.利用迭代器进行遍历:
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<String, Integer>();
scores.put("Tom", 91);
scores.put("Jim", 89);
scores.put("Jack", 95);
Set<String> names = scores.keySet();
Iterator iterator = names.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}//换行依次输出"Tom","Jim","Jack"
}
}
二丶将HashMap集合中key-value用Entry对象包含后进行遍历
1.加强for循环:
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<String, Integer>();
scores.put("Tom", 91);
scores.put("Jim", 89);
scores.put("Jack", 95);
Set<Entry<String, Integer>> entries = scores.entrySet();
for(Entry content : entries) {
System.out.println(content);
}//换行输出为:Tom=91 Jack=95 Jim=89
}
}
2.利用迭代器进行遍历:
public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<String, Integer>();
scores.put("Tom", 91);
scores.put("Jim", 89);
scores.put("Jack", 95);
Set<Entry<String, Integer>> entries = scores.entrySet();
Iterator<Entry<String, Integer>> iterator = entries.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}//换行输出为:Tom=91 Jack=95 Jim=89
}
}
注:上述代码中均省略了引包代码,eclipse用户可利用快捷键CTRL+shift+o进行快速引包操作.