HashMap

发布时间 2023-04-10 17:45:53作者: 为TT
  1.  

     

  2.  

     

  3. 练习1:
     //需求:创建一个HashMap集合,键是学生对象Student,值是籍贯,储存3个键值对对象并遍历,要求同性别,同年龄位同一个学生
    //核心点:如果是键存储自定义对象,需要重写equal和Hashcode方法
    //创建一个map集合
    HashMap<Student,String> hashMap=new HashMap<>();
    //创建对象
    Student student1 = new Student("张三", "25");
    Student student2= new Student("李四", "35");
    Student student3 = new Student("王五", "45");
    //添加元素
    hashMap.put(student1,"江西");
    hashMap.put(student2,"万年");
    hashMap.put(student3,"苏桥");
    //键值对遍历
    Set<Map.Entry<Student, String>> entries = hashMap.entrySet();
    for (Map.Entry<Student, String> entry : entries) {
    Student key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key+value);
    }
    System.out.println("-------------------------------------------------------------");
    //键遍历
    Set<Student> students = hashMap.keySet();
    for (Student key : students) {
    String value = hashMap.get(key);
    System.out.println(value+key);
    }
    System.out.println("-------------------------------------------------------------");
    //lambda表达式遍历
    hashMap.forEach(new BiConsumer<Student, String>() {
    @Override
    public void accept(Student student, String s) {
    System.out.println(student+s);
    }
    });


    }
    }
    class Student{
    private String name;
    private String age;

    public Student() {
    }

    public Student(String name, String age) {
    this.name = name;
    this.age = age;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getAge() {
    return age;
    }

    public void setAge(String age) {
    this.age = age;
    }
    //关于值,重写方法

    @Override
    public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return Objects.equals(name, student.name) &&
    Objects.equals(age, student.age);
    }

    @Override
    public int hashCode() {
    return Objects.hash(name, age);
    }

    @Override
    public String toString() {
    return "Student{" +
    "name='" + name + '\'' +
    ", age='" + age + '\'' +
    '}';
    }
    }