Cách sử dụng HashMap

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;    

public class SetsLession {
   public static void main(String[] args) {
   HashMap hashMap = new HashMap<>();
   hashMap.put("fullname", "Tran Van Chung");
   hashMap.put("age", "30");
   hashMap.put("address", "Hai Phong");
   System.out.println(hashMap.get("fullname"));
   HashMap<Object, Object> hashObj = new HashMap<>();
    hashObj.put(1, "Com");
    hashObj.put(2, "Canh");

    System.out.println(hashObj.get(1));

    HashMap<String, Student> studentList = new HashMap<>();
    Student stu = new Student("SV1","Nguyen Nhu Quynh");
    studentList.put(stu.rollno, stu);
    stu = new Student("SV2", "Hoang Minh Nhi");

    studentList.put(stu.rollno, stu);
    System.out.println(studentList.toString());

    Student std2 = studentList.get("SV1");
    System.out.println("STD2: "+std2);
    studentList.forEach((keyInt, valueInt) -> System.out.println("Key = " + keyInt + ", value = " + valueInt));
    for(String list : studentList.keySet()) {
        System.out.println(list);
    }

    //Cách duyệt các phần tử trong HashMap
    Set<String> keys = hashMap.keySet();
    keys.forEach((key)->{
        System.out.println(key + " : " + hashMap.get(key));
    });
    //kiểm tra key có tồn tại hay không
    boolean keycheck = hashMap.containsKey("address");
    if (keycheck) {
        System.out.println("住所: "+ hashMap.get("address"));
    } else {
        System.out.println("キーが存在しません");
    }


}

}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Chào mừng bạn đến với blog của tôi! Đây là nơi tôi chia sẻ những trải nghiệm, suy nghĩ và kiến thức mà tôi học được trong cuộc sống và công việc. Hy vọng bạn sẽ tìm thấy điều gì đó hữu ích và thú vị tại đây.

Design a site like this with WordPress.com
Get started