集合遍历

 

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

 

posted @ 2019-05-21 00:17  chy_18883701161  阅读(294)  评论(0编辑  收藏  举报