public class Test2 {
public static void main(String[] args) {
Map<Student,String> map = new HashMap<>();
map.put(new Student("胡桃",18),"璃月港");
map.put(new Student("神里凌华",18),"神里屋敷");
map.put(new Student("纳西妲",12),"净善宫");
map.put(new Student("雷神",22),"稻妻城");
Set<Student> keys = map.keySet();
Iterator<Student> it = keys.iterator();
// 方法一:
while (it.hasNext()){
Student key = it.next();
String value = map.get(key);
System.out.println("student:"+key+"adress:"+value);
}
Collection<String> values = map.values();
// 方法二:
for (String value:values) {
System.out.println(value);
}
// 方法三:
Set<Map.Entry<Student,String>> entries = map.entrySet();
for (Map.Entry<Student,String> entry:entries) {
Student key = entry.getKey();
String value = entry.getValue();
System.out.println("student:"+key+"adress:"+value);
}
}
}
public class Student {
String name ;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
三种方式遍历Map集合中的内容
最新推荐文章于 2024-08-05 19:03:51 发布