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遍历 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章