package com.collection_.map_;
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添加3个员工对象,要求
键:员工id
值:员工对象
并遍历显示工资>18000的员工(遍历方式最少两种)
员工类:姓名、工资、员工id
*/
Map hashMap = new HashMap();
hashMap.put(1,new Employee("张三",19000,1));
hashMap.put(2,new Employee("李四",16000,2));
hashMap.put(3,new Employee("王五",30000,3));
//1. 使用keySet来遍历
Set keySet = hashMap.keySet();
//增强for
System.out.println("========keySet 增强for遍历");
for (Object key : keySet) {
//取出value(转换成 employee对象才可以调用Salary)
Employee emp = (Employee) hashMap.get(key);
if (emp.getSalary()>18000) {
System.out.println(key +"-" + hashMap.get(key));
}
}
//迭代器
System.out.println("========keySet 迭代器遍历");
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
Employee emp = (Employee) hashMap.get(key);
if (emp.getSalary()>18000) {
System.out.println(key +"-" + hashMap.get(key));
}
}
//2. 通过EntrySet遍历
Set entrySet = hashMap.entrySet();
//增强for
System.out.println("========Entry 增强for遍历");
for (Object entry :entrySet) {
//转换成Map.Entry 调用getKey() 和getValue()
Map.Entry m = (Map.Entry) entry;
//取出value
Employee emp = (Employee) m.getValue();
if (emp.getSalary()>18000) {
System.out.println(m.getKey() +"-" + m.getValue());
}
}
//迭代器
System.out.println("========EntrySet 迭代器遍历");
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()){
Object entry = iterator2.next();//Map.Entry entry = (Map.Entry) iterator2.next();
//转换成Map.Entry 调用getKey() 和getValue()
Map.Entry m = (Map.Entry) entry;
//取出value
Employee emp = (Employee) m.getValue();
if (emp.getSalary()>18000) {
System.out.println(m.getKey() +"-" + m.getValue());
}
}
}
}
//员工类:姓名、工资、员工id
class Employee{
private String name;
private double salary;
private int id;
public Employee(String name, double salary, int id) {
this.name = name;
this.salary = salary;
this.id = id;
}
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 getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", salary=" + salary +
", id=" + id +
'}';
}
}
Map练习
最新推荐文章于 2021-11-10 11:02:33 发布