zoukankan      html  css  js  c++  java
  • 集合遍历

    1、使用增强的for循环

    1  HashMap hashMap=new HashMap();
    2         hashMap.put("name","张三");
    3         hashMap.put("age",12);
    4         hashMap.put("score",90);
    5         for (Object key:hashMap.keySet()){
    6             System.out.println(key+" --> "+hashMap.get(key));
    7         }

    此种方式可以遍历所有集合,但使用的是临时变量,只能访问集合元素,不能修改。

    2、Collection集合可以使用自身的 forEach(Consumer  action)方法,Consumer是一个函数式接口,只需实现 accept(element)方法。

    1 HashSet hashSet=new HashSet();
    2        hashSet.add("张三");
    3        hashSet.add("李四");
    4        hashSet.add("王五");
    5        //参数表示当前元素
    6        hashSet.forEach(ele-> System.out.println(ele));

    此方式只能用于Collection集合。

    3、Map集合也可以使用自身的forforEach(BiConsumer action),BiConsumer是一个函数式接口,只需要实现accept(key,value)方法。

    1  HashMap hashMap=new HashMap();
    2        hashMap.put("name","张三");
    3        hashMap.put("age",18);
    4        hashMap.put("score",90);
    5        //2个参数,一个代表键,一个代表对应的值
    6        hashMap.forEach((key,value)-> System.out.println(key+" --> "+value));

    此方式只能用于Map集合。

    4、使用Iterator接口

    Iterator即迭代器,可用的4个方法:

    boolean  hasNext()

    Object  next()     获取下一个元素

    void  remove()    删除当前元素

    void  forEachRemaining(Consumer action)    可以使用Lambda表达式遍历集合

    1  HashSet hashSet=new HashSet();
    2        hashSet.add("张三");
    3        hashSet.add("李四");
    4        hashSet.add("王五");
    5        //获取迭代器对象
    6        Iterator iterator=hashSet.iterator();
    7        while (iterator.hasNext()){
    8            System.out.println(iterator.next());
    9        }
    1 HashSet hashSet=new HashSet();
    2        hashSet.add("张三");
    3        hashSet.add("李四");
    4        hashSet.add("王五");
    5        //获取迭代器对象
    6        Iterator iterator=hashSet.iterator();
    7        iterator.forEachRemaining(element-> System.out.println(element));

    以上两种方式效果完全相同。

    说明:

    Collection集合才能使用此方式,因为Collection集合才提供了获取Iterator对象的方法,Map未提供。

    List集合还可以使用 listIterator() 获取 ListIterator对象,ListIterator是Iterator的子接口,使用方式和Iterator完全相同,只是ListIterator还提供了其它方法。

    在循环体中不能使用集合本身的删除方法来删除元素,会发生异常。要删除,只能使用Iterator类提供的remove()方法来删除。

  • 相关阅读:
    面试官:请说一下对象锁和类锁的区别
    手撕 JVM 垃圾收集日志
    JVM 问题排查和性能优化常用的 JDK 工具
    JVM 中你不得不知的一些参数
    微信授权就是这个原理,Spring Cloud OAuth2 授权码模式
    基准测试了 ArrayList 和 LinkedList ,发现我们一直用 ArrayList 也是没什么问题的
    Spring Cloud OAuth2 实现用户认证及单点登录
    后端开发有必要学习前端吗,如何入门呢
    无意间做了个 web 版的 JVM 监控端(前后端分离 React+Spring Boot)
    走进AngularJs(一)angular基本概念的认识与实战
  • 原文地址:https://www.cnblogs.com/chy18883701161/p/10897500.html
Copyright © 2011-2022 走看看