HashMap兩種遍歷方式
阿新 • • 發佈:2022-03-20
package com.czie.iot1913.lps.Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author [email protected]
* @date 2022-03-20 20:24
*/
public class MapTest06 {
public static void main(String[] args) {
HashMap<String,Student> map = new HashMap<String,Student>();
Student s1 = new Student("劉品水",21);
Student s2 = new Student("品水",22);
Student s3 = new Student("劉",27);
map.put("158",s1);
map.put("159",s2);
map.put("160",s3);
Set<String> set = map.keySet();
for (String s:set){
Student key = map.get(s);
System.out.println(s+","+key.getName()+","+key.getAge());
}
System.out.println("==================");
Set<Map.Entry<String, Student>> entry = map.entrySet();
for (Map.Entry<String, Student> e:entry){
String key01 = e.getKey();
Student value01 = e.getValue();
System.out.println(key01+","+value01.getName()+","+value01.getAge());
}
}
}
package com.czie.iot1913.lps.Map;
/**
* @author [email protected]
* @date 2022-03-20 20:28
*/
public class Student {
private String name;
private int 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;
}
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}