JAVA Iterator 转成 List


List转到Iterator容易,JDK本身就支持,反过来的实现方式如下:

1.使用Apache Common Collections 

2.自己实现的方法转换

3.Guaa实现转换


[java] view plain copy
  1. 方式1:  
  2. #Apache Commons Collections:  
  3. import org.apache.commons.collections.IteratorUtils;  
  4. Iterator<Element> myIterator = //some iterator  
  5. List<Element> myList=IteratorUtils.toList(myIterator);     
  6.   
  7.   
  8. 方式二:  
  9. 或者自己转换  
  10. public static <T> List<T> copyIterator(Iterator<T> iter) {  
  11.     List<T> copy = new ArrayList<T>();  
  12.     while (iter.hasNext())  
  13.         copy.add(iter.next());  
  14.     return copy;  
  15. }  
  16.   
  17. 使用方式:  
  18. List<String> list = Arrays.asList("1""2""3");  
  19. Iterator<String> iter = list.iterator();  
  20. List<String> copy = copyIterator(iter);  
  21.   
  22. 方式3:  
  23. #Guava  
  24. import com.google.common.collect.Lists;  
  25. Iterator<Element> myIterator =  //some iterator  
  26. List<Element> myList = Lists.newArrayList(myIterator); 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM