Map课堂练习
Map接口和常用方法
使用HashMap添加3个员工对象,要求
键:员工id
值:员工对象
并遍历显示工资>18000的员工(遍历方式最少两种)
员工类:姓名、工资、员工id
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@SuppressWarnings({"all"})
public class MapExercise {
public static void main(String[] args) {
//创建一个HashMap
Map hashMap = new HashMap();
//放入三个员工对象
hashMap.put(1, new Employee("test1", 17000, 1));
hashMap.put(2, new Employee("test2", 19000, 2));
hashMap.put(3, new Employee("test3", 20000, 3));
//1.使用keySet -> 增强for
Set keySet = hashMap.keySet();
for (Object key : keySet) {
Employee employee = (Employee) hashMap.get(key);
if (employee.getSalary() > 18000) {
System.out.println(employee);
}
}
//2.使用entrySet -> 迭代器
Set entrySet = hashMap.entrySet();
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
//通过entry取得key和value
Employee employee = (Employee) entry.getValue();
if (employee.getSalary() > 18000) {
System.out.println(employee);
}
}
}
}
//创建员工对象
class Employee {
private String name;//姓名
private double salary;//工资
private int eid;//员工id
public Employee(String name, double salary, int eid) {
this.name = name;
this.salary = salary;
this.eid = eid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", salary=" + salary +
", eid=" + eid +
'}';
}
}