常用的集合遍历操作有:Lambda表达式遍历、Iterator遍历、Lambda表达式遍历Iterator、foreach遍历集合元素。
- Lambda表达式遍历:Collection extends Iterable,Iterable接口中有个默认方法:
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
/**
当调用Iterable的foreach(Consumer<? super T> action)时,程序将集合元素传递给接口Consumer(函数式接口)的唯一抽象方法:void accept(T t)
通过该方法可实现对集合的遍历,实例如下:
*/
public class SDF
{
public static void main(String[] args)
{
Collection c = new HashSet<>();
c.add("ele1");
c.add("ele2");
c.add("ele3");
c.forEach(obj -> System.out.println("迭代集合器:" + obj));
}
}
控制台输出(Set集合无序不可重复,输出结果的顺序与add的顺序无关,可尝试打印集合c,其与元素的HashCode值有关—>下同):
迭代集合器:ele3
迭代集合器:ele2
迭代集合器:ele1
- Iterator遍历:查看Iterator的API:
public interface Iterator
An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
- Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
- Method names have been improved.
This interface is a member of the Java Collections Framework.
Iterator必须在集合类的基础上生成,即存在一个Iterator对象(迭代器),则必有一个与之关联的Collection对象;
Iterator接口中有函数:void forEachRemaining(Consumer
public class SDF
{
public static void main(String[] args)
{
Collection c = new HashSet<>();
c.add("ele1");
c.add("ele2");
c.add("ele3");
Iterator it1 = c.iterator();
System.out.println(it1.hasNext());
while (it1.hasNext())
{
System.out.println("--->" + it1.next());
}
}
}
控制台输出结果:
true
--->ele3
--->ele2
--->ele1
- Lambda表达式遍历Iterator: forEachRemaining的参数仍然时函数式接口对象,因而同样可以采用Lambda表达式;
代码如下:
public class SDF
{
public static void main(String[] args)
{
Collection c = new HashSet<>();
c.add("ele2");
c.add("ele4");
c.add("ele3");
Iterator it = c.iterator();
it.forEachRemaining(ob -> System.out.println("迭代器:" + ob));
/* Iterator it1 = c.iterator();
System.out.println(it1.hasNext());
while (it1.hasNext())
{
System.out.println("--->" + it1.next());
}*/
}
}
控制台输出结果:
迭代器:ele4
迭代器:ele3
迭代器:ele2
- foreach遍历集合元素:
public class SDF
{
public static void main(String[] args)
{
Collection c = new HashSet<>();
c.add("ele2");
c.add("ele4");
c.add("ele3");
for (Object object : c)
{
System.out.println("foreach-->" + object);
}
}
}
控制台输出:
foreach-->ele4
foreach-->ele3
foreach-->ele2
- 同一个Iterator对象(迭代器),只能进行一次遍历,因为遍历完之后其不具有任何元素:
public class SDF
{
public static void main(String[] args)
{
Collection c = new HashSet<>();
c.add("ele1");
c.add("ele4");
c.add("ele3");
Iterator it = c.iterator();
it.forEachRemaining(obj -> System.out.println("迭代器:" + obj));
System.out.println(it.hasNext());
while (it.hasNext())
{
System.out.println("--->" + it.next());
}
}
}
控制台输出:
迭代器:ele4
迭代器:ele3
迭代器:ele1
false