遍历集合中的元素

public class CollectionEach {

    public static void main(String[] args) {
        Collection<String> collection = new HashSet();
        collection.add("hello");
        collection.add(",");
        collection.add("ironman");
//        遍历集合中的元素 :
//① 使用 Iterator 对象(迭代器)
        Iterator it = collection.iterator();
        while (it.hasNext()) {
            Object next = it.next();
            System.out.println(next);
            //用这种方式遍历集合元素时,集合中的元素不能被改变,只能通过iterator 的remove()方法删除上一次next()方法返回的集合元素。
        }
//② iterable 接口是collection的父接口 ,所以可以使用 iterable 接口中的forEach (Consumer action)方法,该方法接收的参数是一个函数式接口 。
        //当程序调用Iterable 的forEach遍历集合元素时,程序会依次将集合元素传给consumer的accept(T t)方法。
        collection.forEach(obj -> System.out.println(obj));
//③使用iterator 对象的 forEachRemaining(Consumer action ) 方法
        Iterator iterator = collection.iterator();
        iterator.forEachRemaining(obj -> System.out.println(obj));
//④使用foreach循环
        for (String string : collection) {
            System.out.println(string);
            //同样的,使用foreach循环遍历集合时,该集合也不能被改变。
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值