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 Type | Method and Description |
---|---|
default void | forEach(Consumer<? super T> action) Performs the given action for each element of the Iterableuntil 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 Spliteratorover 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.迭代器,遍历是要用的,很重要 |
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 trueif 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<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);
}
相关文章推荐
- 搭建Spring、Spring MVC、Mybatis和Freemarker
- 利用BeanMap进行对象与Map的相互转换
- 在eclipse4.5.1官方英文版利用官方语言包汉化的方法
- java线程学习(四)---线程间的通信
- RxJava教程(一)
- 浅谈springSecurity
- Intellij idea处理Spring MVC单元测试问题
- GWT 项目创建
- windows下java操作zookeeper
- myeclipse中配置jbmp3.2.1
- zigbee网关 java 串口通信
- 【Developer Log】Java1.8在J2EE中疑似leak的修正
- Spring注解@Component、@Repository、@Service、@Controller区别
- Java枚举类"全方位"
- SpringMVC返回json数据的三种方式
- Java枚举类"全方位"
- Java对象序列化用法
- Description Resource Path Location Type Java compiler level does not match the version of the instal
- spring3.0的BeanFactory上下文context获取不到bean
- 基于JDK http包实现的简单代理服务器