Java中的Map和Set

public class TestMap {
    //一個Map只能維護一組映射關係,若需要多組映射,就需要多個Map。
    //只能通過key找到value
    //對於get方法,如果key不存在,返回null
    //對於getOrDefault,如果key不存在,返回默認值
    //put方法若key不存在,就會創建新的鍵值對
    //若存在,就會修改value的值

    public static void main(String[] args) {
        Student s1 = new Student("蔡徐坤",20,"大四","北京大學");
        Student s2 = new Student("羅志祥",30,"大三","家裏蹲");
        Student s3 = new Student("人才",40,"大一","外國語");
        Map<String,Student> studentMap = new HashMap<>();
        studentMap.put(s1.name,s1);
        studentMap.put(s2.name,s2);
        studentMap.put(s3.name,s3);
        String name = "蔡徐坤";
        String name1 = "厲害";
        Student student = studentMap.get(name);
        Student student1 = studentMap.getOrDefault(name1,new Student("moren ",10,"moren","moren"));

        System.out.println(student);
        System.out.println(student1);

        //遍歷一個Map
        for (Map.Entry<String,Student> entry:studentMap.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
    }
}
public class TestSet {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();

        set.add("JAVA");
        set.add("JAVA");
        set.add("JAVA");
        set.add("C++");
        set.add("Python");
        set.add("JS");
        //判定某個元素是否再set中存在
        System.out.println(set.contains("JAVA"));
        //刪除元素
        set.remove("C++");
        System.out.println(set.contains("C++"));
        System.out.println(set);
        //可以幫助我們進行去重
        //foreach遍歷set    是迭代器的簡化版本
        for (String s:set) {
            System.out.println(s);
        }
        //使用迭代器來遍歷集合類
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
//set和Map裏面的元素的順序和插入順序無關
//只有實現了iterable的對象纔可以使用for each遍歷 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章