方法一
加强循环:
Map<String,Integer> scores = new HashMap<String,Integer>();
scores.put("Jim", 100);
scores.put("Kate", 10);
Set<String> names = scores.keySet();
//获取集合中所有key-value的key组成的Set集合"Jim" "Kate"
for (String key : names) {
int value = scores.get(key);
System.out.println(value);
}
迭代循环:
Iterator<String> iterator = names.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
int value = scores.get(key);
System.out.println(value);
}
方法二
加强循环:
Set<Entry<String, Integer>> entries = scores.entrySet();
//将HashMap集合中key-value用Entry对象包含
for (Entry<String, Integer> entry : entries) {
String key = entry.getKey();
int value = entry.getValue();
System.out.println(value);
}
迭代循环:
Iterator<Entry<String, Integer>> it = entries.iterator();
while(it.hasNext()) {
Entry<String, Integer> entry = it.next();
String key = entry.getKey();
int value = entry.getValue();
System.out.println(value);
}
方法总览:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Test4 {
public static void main(String[] args) {
Map<String,Integer> scores = new HashMap<String,Integer>();
scores.put("Jim", 100);
scores.put("Kate", 10);
//第一种
Set<String> names = scores.keySet();//获取集合中所有key-value的key组成的Set集合"Jim" "Kate"
//加强循环
for (String key : names) {
int value = scores.get(key);
System.out.println(value);
}
//迭代器
Iterator<String> iterator = names.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
int value = scores.get(key);
System.out.println(value);
}
//第二种
Set<Entry<String, Integer>> entries = scores.entrySet();//将HashMap集合中key-value用Entry对象包含
//加强循环
for (Entry<String, Integer> entry : entries) {
String key = entry.getKey();
int value = entry.getValue();
System.out.println(value);
}
//迭代器
Iterator<Entry<String, Integer>> it = entries.iterator();
while(it.hasNext()) {
Entry<String, Integer> entry = it.next();
String key = entry.getKey();
int value = entry.getValue();
System.out.println(value);
}
}
}