发布时间:2023-10-30 14:30
调用keySet方法:
@Test
public void getKeys1(){
Map map = new HashMap<>();
map.put("name","曹操");
map.put("sex","男");
map.put("age","21");
System.out.println("map.keySet():"+map.keySet());
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()){
System.out.println("iterator:"+iterator.next());
}
Set keySet = map.keySet();
// 遍历keySet,并输出key的值
for(String key : keySet){
System.out.println(key+":"+map.get(key).toString());
}
}
输出:
map.keySet():[sex, name, age]
iterator:sex
iterator:name
iterator:age
sex:男
name:曹操
age:21
entrySet()
@Test
public void getKeys2(){
Map map = new HashMap<>();
map.put("name","曹操");
map.put("sex","男");
map.put("age","21");
//第二种
System.out.println("map.entrySet():"+map.entrySet());
Iterator> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
System.out.println("iterator:"+iterator.next());
}
for (Map.Entry entry : map.entrySet()){
System.out.println("key:"+entry.getKey()+";value:"+entry.getValue());
}
}
输出:
map.entrySet():[sex=男, name=曹操, age=21]
iterator:sex=男
iterator:name=曹操
iterator:age=21
key:sex;value:男
key:name;value:曹操
key:age;value:21
参考链接:
https://www.cnblogs.com/cailijuan/p/10687995.html