首页 > 其他 > 详细

集合遍历

时间:2019-05-21 00:34:26      阅读:115      评论:0      收藏:0      [点我收藏+]

 

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()方法来删除。

 

集合遍历

原文:https://www.cnblogs.com/chy18883701161/p/10897500.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!