您的位置:首页 > 编程语言 > Java开发

java集合框架遍历元素方法总结

2015-12-04 17:02 585 查看

遍历集合的方法的总结:

知道了Collection主接口的所有方法之后,对遍历结合的方法进行一个全面的总结:

方法1 使用iterable接口下的foreach方法:从api可以知道Collection这个主接口是继承了Iterable接口的,所以iterable提供的遍历方法,collection的实现结合类都可以用此方法进行遍历元素
(public interface Collection<E>extendsIterable<E>)

iterable方法如下:

APIjava8官方文档:http://docs.oracle.com/javase/8/docs/api/

Modifier and TypeMethod and Description
default void
forEach(Consumer<?
super T> action)


Performs the given action for each element of the
Iterable
until all elements have been processed or the action throws an exception.
Iterator<T>
iterator()


Returns an iterator over elements of type
T
.
default Spliterator<T>
spliterator()


Creates a
Spliterator
over
the elements described by this
Iterable
.
测试代码如下:

public class ForeachOfIterable {
public static void  main(String[] args){
Collection<String> coll = new ArrayList<String>();
coll.add("book1");
coll.add("dog1");
coll.add("cat1");
coll.forEach((object)->{System.out.println("arraylist下包含"+object);});
}
}


方法2 使用collection的iterator方法返回iterator接口:

Iterator<E>
iterator()


Returns an iterator over the elements in this collection.迭代器,遍历是要用的,很重要
iterator<>方法如下:

default void
forEachRemaining(Consumer<?
super E> action)


Performs the given action for each remaining element until all elements have been processed or the action throws an exception.
boolean
hasNext()


Returns
true
if the iteration has more elements.
E
next()


Returns the next element in the iteration.
default void
remove()


Removes from the underlying collection the last element returned by this iterator (optional operation).
这种方法需要注意的是:当使用iterator迭代访问collection集合元素的过程中,collection集合里的元素是不能被改变的,

Iterator<String> it = coll.iterator();

while(it.hasNext()){

String book = it.next();

System.out.println(book);

if(book.equals("book1")){

coll.remove(book);

}

}

会出现" java.util.ConcurrentModificationException异常。

测试代码如下:

//2.使用collection的iterator方法
Iterator<String> it = coll.iterator();
while(it.hasNext()){
System.out.println(it.next());
}


方法3:使用iterator接口的foreachRemaining方法:

api如上所视,测试代码如下:

//3.使用foreachRemaining方法

Iterator<String> itt = coll.iterator();

itt.forEachRemaining((obje)->{System.out.println(obje);} );

方法4:使用java5中foreach循环方法:

//4.使用foreach循环

for (Object object1 :hascoll) {

System.out.println(object1);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: