ort java.util.*;
import java.util.HashSet;
public class CllectionEach {
public static void main(String[] args)
{
Collection books = new HashSet();
books.add("guodongTest");
books.add("我的java");
books.add("测试方法用的");
books.forEach(obj -> System.out.println("迭代输出集合中的元素 " + obj));
//forEach方法是用来遍历集合的,一次将集合的元素传给Consumer的accept法官法(该借口中的唯一的方法)因此consumer是函数式接口,可以使用lambda表达式
//forEach方法是将集合元素逐个传给Lambda表达式的形参,这样实现了lambda逐个输出集合中的元素
/*定义一个Iterator对象,Iterator本身不提供盛装其他对象的功能,它是一个迭代器
在Iterator中提供了四个方法 hasNext() next() remove() forEachRemaining()四个方法,用于迭代集合中的数据
*/
Iterator it = books.iterator();
while(it.hasNext())
{
String book = (String)it.next();
System.out.println(book);
}
/*
Iterator必须以来与Collection对象,若有一个Iterator对象则必有一个Collection的对象
Iterator只提供迭代输出集合中的对象的功能,不能对结合中的对象进行修改的操作
* */
Iterator itt = books.iterator();
//forEachRemaining是在Iterator中的一个方法,用于迭代输出集合中的元素的,而forEach方法是在Collection的对象中使用的方法
itt.forEachRemaining(obj -> System.out.println("输出集合中的元素 " + obj));
//集合的元素同样还可以使用java5中提供的foreach的方法来输出集合中的元素
for (Object obj:books)
{
String book = (String)obj;
System.out.println(book);
}
}
}
java中的Iterator迭代器的使用
最新推荐文章于 2022-05-03 10:42:23 发布