import java.util.*;
public class IteratorTest
{
public static void main(String[] args)
{
System.out.println("使用Lambda表达式遍历集合");
var books = new HashSet();
books.add("轻量级JavaEE企业应用实战");
books.add("疯狂Java讲义");
books.add("疯狂Android讲义");
books.forEach( s -> System.out.println("迭代集合元素:"+s));
System.out.println("使用Iterator遍历集合元素");
Iterator it = books.iterator();
while(it.hasNext())
{
String book = (String) it.next();
System.out.println(book);
if(book.equals("疯狂Java讲义"))
{
//it.remove();//这个是允许的
books.remove(book);//这个是不允许的,如果不是最后一个元素,也就是说,remove后还会调用it.next(),就会报错
}
}
System.out.println("");
System.out.println(books);
System.out.println();
System.out.println("使用Lambda表达式遍历Iterator");
it = books.iterator();
it.forEachRemaining( s -> System.out.println("迭代集合元素:"+s));
System.out.println();
System.out.println("使用foreach循环遍历集合元素");
for(var b : books)
{
System.out.println(b instanceof String);
if(b.equals("轻量级JavaEE企业应用实战"))
{
books.remove(b);
}
}
}
}
Java练习四种方式遍历集合
最新推荐文章于 2022-12-07 15:25:04 发布