1. 程式人生 > >定義一個Map物件,遍歷並打印出各元素的key和value

定義一個Map物件,遍歷並打印出各元素的key和value

    //建立HashMap 集合  泛型為 Person 類
    HashMap<Person, String> hm = new HashMap<>();
    //向集合中新增資料   key為Person物件   value為字串
    hm.put(new Person("顧雨磊",25), "河北");
    hm.put(new Person("周紅偉",23), "杭州");
    hm.put(new Person("黑馬",20), "上海");
    hm.put(new Person("程式設計師",18), "北京");
    hm.put(new Person("IT人",1), "中國");
    /*第一種方法
    遍歷並打印出各元素的key和value
    hm.keySet()獲取key及學生物件*/
    System.out.println("...........第一種方法使用hm.keySet()...........");
    for (Person personkey : hm.keySet()) {
        System.out.println("姓名: "+personkey.getName()+", 年齡: "+personkey.getAge()+", 來自: "+hm.get(personkey));
    }
    System.out.println("...........第二種方法使用hm.entrySet()...........");
    /*第二種方法遍歷*/
    for (Entry<Person, String> en : hm.entrySet()){
        System.out.println("姓名: "+en.getKey().getName()+", 年齡: "+en.getKey().getAge()+", Value: "+en.getValue());

    }