JAVA Iterator 轉(zhuǎn)成 List 的操作
List轉(zhuǎn)到Iterator容易,JDK本身就支持,反過來的實現(xiàn)方式如下:
1.使用Apache Common Collections
2.自己實現(xiàn)的方法轉(zhuǎn)換
3.Guaa實現(xiàn)轉(zhuǎn)換
方式1:
#Apache Commons Collections:import org.apache.commons.collections.IteratorUtils;Iterator<Element> myIterator = //some iteratorList<Element> myList=IteratorUtils.toList(myIterator);
方式2:
或者自己轉(zhuǎn)換
public static <T> List<T> copyIterator(Iterator<T> iter) { List<T> copy = new ArrayList<T>(); while (iter.hasNext()) copy.add(iter.next()); return copy;}
使用方式:
List<String> list = Arrays.asList('1', '2', '3');Iterator<String> iter = list.iterator();List<String> copy = copyIterator(iter);
方式3:
#Guavaimport com.google.common.collect.Lists;Iterator<Element> myIterator = //some iteratorList<Element> myList = Lists.newArrayList(myIterator);
補充:數(shù)組與List、Arraylist互相轉(zhuǎn)換,迭代器Iterator的一些用法
一、數(shù)組轉(zhuǎn)換為List或ArrayList
1.String類型數(shù)組轉(zhuǎn)換為ArrayList
public void test(){ String[] str = {'first','second','third'}; ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(str)); }
asList(T):返回由指定數(shù)組支持的固定大小的列表。
2.int類型數(shù)組轉(zhuǎn)換為List
public void test(){ int[] nums = {5,6,8,4,7,3}; List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList()); }
Arrays.stream將 int[] 轉(zhuǎn)換成 IntStream.
使用IntStream.boxed()進行裝箱,將IntStream轉(zhuǎn)換成Stream.
Stream.collect()將Stream轉(zhuǎn)換成List,得到List.
二、List轉(zhuǎn)換為數(shù)組
toArray()方法
public void test(){ List<String> list = new ArrayList<String>(); list.add('first'); list.add('second'); String[] str1 = list.toArray(new String[list.size()]); }
三、Iterator遍歷List
public void test(){ List<String> list = new ArrayList<String>(); list.add('first'); list.add('second'); for(Iterator<String> i = list.iterator(); i.hasNext();){ String str = i.next(); System.out.println(str); } }
hasNext():如果迭代具有更多的元素,則返回true 。用于判定List是否還有元素,有則返回true,繼續(xù)迭代。
next():返回迭代中的下一個元素。用來獲取元素。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. 理解PHP5中static和const關(guān)鍵字2. IntelliJ IDEA安裝插件的方法步驟3. php模擬實現(xiàn)斗地主發(fā)牌4. .Net Core使用Coravel實現(xiàn)任務(wù)調(diào)度的完整步驟5. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實現(xiàn)6. jQuery 實現(xiàn)DOM元素拖拽交換位置的實例代碼7. Vuex localStorage的具體使用8. vue 使用localstorage實現(xiàn)面包屑的操作9. spring acegi security 1.0.0 發(fā)布10. MyBatis中的JdbcType映射使用詳解

網(wǎng)公網(wǎng)安備