• Map集合


    Map是双列集合顶层集合是所有双列集合都可以使用的

    Map是接口,不能直接创建对象,可以创建它的实现类的对象;

    put方法:添加数据时键不存在则添加,返回null,如果存在则覆盖原有键值对对象,并返回被覆盖的值对象。

    remove:返回被删除的值对象,如果不存在返回null;

    containsKey,containsValue:判断键或值是否存在

    size:返回集合中键值对的个数;

    1. Map map=new HashMap<>();
    2. map.put("mike","jane");
    3. map.put("mke","jne");
    4. map.put("mie","jae");
    5. map.put("mik","jan");
    6. String val=map.put("mike","maarie");
    7. map.remove("mike");
    8. System.out.println(map);
    9. System.out.println(val);

    Entry集合就是pair<>对象;java没有tuple;Entry是Map的内部接口;不写Map时要导入Map包;

    1. //1.创建Map集合的对象
    2. Map map=new HashMap<>();
    3. map.put(new Student("zhangsan",23),"江苏");
    4. map.put(new Student("lisi",24),"上海");
    5. map.put(new Student("wangwu",25),"福建");
    6. map.put(new Student("heliu",26),"陕西");
    7. //Map集合的遍历:
    8. // 1。获取键值,根据键值遍历 Setkeys=map.keySet();
    9. //2.获取整个集合的pair对象,进行遍历; Set>entiries=map.entrySet();
    10. //使用foreach进行遍历;
    11. //单独获取健对象
    12. Setkeys=map.keySet();
    13. for(Student stu:keys)
    14. {
    15. //根据键获得值
    16. String value=map.get(stu);
    17. System.out.println(stu+" = "+value);
    18. }
    19. System.out.println("_____________________________");
    20. //获取pair对象
    21. Set>entiries=map.entrySet();
    22. for(Map.Entryentry:entiries)
    23. {
    24. System.out.println(entry.getKey()+" = "+entry.getValue());
    25. }
    26. System.out.println("_____________________________");
    27. //使用foreach进行遍历
    28. map.forEach(new BiConsumer() {
    29. @Override
    30. public void accept(Student student, String s) {
    31. System.out.println(student+" = "+s);
    32. }
    33. });

    HashMap的键对象如果是自定义对象,就需要重写hashCode方法以及equals方法

    LinkedHashMap

    增加了双向链表机制,保证遍历顺序与存储顺序一致;

    TreeMap

    TreeSet,TreeMap的键值如果是自定义对象需要实现Comparabale接口里的comapreTo方法;

  • 相关阅读:
    Java网络编程——BIO阻塞IO
    JS力扣刷题经典100题——两数相加
    面试经典(5/150)多数元素
    基于centos、alpine制作Java JDK基础镜像
    php代码审计之——phpstorm动态调试
    继承 Inheritance
    LeetCode 面试题 08.14. 布尔运算
    selenium学习
    重制版day 10 字符串相关方法
    基于Docker和Springboot两种方式安装与部署Camunda流程引擎
  • 原文地址:https://blog.csdn.net/qq_41790844/article/details/132841031