首先创建map集合
//创建
HashMap<String,User> userMap=new HashMap<String,User>();
//put方法赋值
userMap.put("james",new User("james","111"));
userMap.put("kobe",new User("kobe","123"));
1、迭代器遍历,根据key
Set<String> keySet=userMap.KeySet();
Iterator<String> iterator=keySet.iterator();
while(iterator.hasnext()){
String key=iterator.next();
System.out.println("key="+key+",value="+userMap.get(key));
}
2、根据entrySet遍历
Set<Map.Entry<String,User>> entries=userMap.entrySet();
for(Map.Entry<String,User> entry:entries){
System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
}
3、直接遍历value
Collection<User> values=userMap.values();
for(User value:values){
System.out.println(value);
}
网友评论