JAVA中的Map的基本操作
程序员文章站
2022-06-28 16:31:05
import java.util.*;public class bianliMap { public static void main(String[] args) { Map map = new HashMap(); map.put("a",1); map.put("b",2); map.put(3,"c"); // 遍历所有的键 Set set = map.keySet(); Sys...
import java.util.*;
public class bianliMap {
public static void main(String[] args) {
Map map = new HashMap();
map.put("a",1);
map.put("b",2);
map.put(3,"c");
// 遍历所有的键
Set set = map.keySet();
System.out.println(set); //[a, b, 3]
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
// 遍历所有的值
Collection values = map.values();
System.out.println(values);//[1, 2, c]
for (Object obj : values){
System.out.println(obj);
}
// 遍历所有的值
Set key = map.keySet();
Iterator iterator1 = key.iterator();
while (iterator1.hasNext()){
Object o = iterator1.next();
Object o1 = map.get(o);
System.out.println(o1);
}
// 遍历所有的key--value,Map.Entery中有getKey()和getValue()方法
Set set1 = map.entrySet();
System.out.println(set1); //[a=1, b=2, 3=c]
Iterator iterator2 = set1.iterator();
while (iterator2.hasNext()){
Object next = iterator2.next();
Map.Entry next1 = (Map.Entry) next;
System.out.println(next1.getKey()+ "===>"+ next1.getValue());
System.out.println(next1);
}
}
}
本文地址:https://blog.csdn.net/wht1000001000wyw/article/details/110283090