<span>Map集合的遍历方法</span>
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestC{
public static void main(String[] args) {
Map map = new HashMap();
map.put(1, 123);
map.put(2, 187);
map.put(3, 44);
System.out.println(map);
//遍历所有的key集:keySet()
Set keySet = map.keySet();
Iterator iterator = keySet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//遍历所有的value集:values()
Collection values = map.values();
for(Object obj: values){
System.out.println(obj);
}
//遍历所有的key-value
Set set = map.keySet();
Iterator iterator1 = set.iterator();
while(iterator1.hasNext()){
Object key = iterator1.next();
Object value = map.get(key);
System.out.print("["+key+","+value+"]"+",");
}
}
}
运行结果:
{1=123, 2=187, 3=44}
1
2
3
123
187
44
[1,123],[2,187],[3,44],