public class MapExercise {
public static void main(String[] args) {
/**
使用 HashMap 添加 3个员工对象,要求:
键:员工id
值:员工对象
遍历显示工资 > 18000 的员工 (最少用两种遍历方式)
员工类:姓名、工资、员工id
*/
Map map = new HashMap();
map.put("01",new Emp("小米",14000,1));
map.put("02",new Emp("华为",19000,2));
map.put("03",new Emp("魅族",13000,3));
map.put("04",new Emp("三星",20000,4));
Set keyset = map.keySet();//先取出所有的Key,通过Key 取出对应的Value
//增强for
for (Object key : keyset) {
//先获取value
Emp emp = (Emp) map.get(key);
if (emp.getSal()>18000)
System.out.println(key+"——"+map.get(key));
}
System.out.println("——————————————————————————————————————");
//迭代器
Set entrySet = map.entrySet();
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
//通过entry取得 key 和 value
Emp emp = (Emp) entry.getValue();
if (emp.getSal()>18000)
System.out.println(entry.getKey()+"——"+emp);
}
}
}
class Emp{
private String name;
private double sal;
private int id;
public Emp(String name, double sal, int id) {
this.name = name;
this.sal = sal;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Emp{" +
"name='" + name + '\'' +
", sal=" + sal +
", id=" + id +
'}';
}
}
输出:
02——Emp{name='华为', sal=19000.0, id=2}
04——Emp{name='三星', sal=20000.0, id=4}
——————————————————————————————————————
02——Emp{name='华为', sal=19000.0, id=2}
04——Emp{name='三星', sal=20000.0, id=4}