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循环遍历集合时,该集合也不能被改变。
}
}
}
遍历集合中的元素
最新推荐文章于 2023-05-24 19:57:36 发布