當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Collection iterator()用法及代碼示例


Java 集合接口的 iterator() 方法返回此集合中元素的迭代器。

用法

public Iterator <E> iterator()

參數

NA

返回

iterator() 方法返回一個遍曆此集合中元素的迭代器。

例子1

import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaCollectionIteratorExample1 {
    static int i = 1;
    public static void main(String[] args) {
        Collection<String> collection = new ConcurrentLinkedQueue<String>();
        collection.add("Ram");
        collection.add("Sham");
        collection.add("Mira");
        collection.add("Rajesh");
        Iterator<String> iterator = collection.iterator();
        //Returns an iterator over the elements
        while (iterator.hasNext()) {
            System.out.println(i++ + "." + iterator.next());
        }
    }
}

輸出:

1.Ram
2.Sham
3.Mira
4.Rajesh

例子2

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
public class JavaCollectionIteratorExample2 {
    public static void main(String[] args) {
        Integer[] val = new Integer[2];
        Collection<Integer> collection = new ConcurrentLinkedQueue<Integer>();
        collection.add(71018);
        collection.add(8000);
        collection.add(1178);
        collection.add(1190);
        //Returns an iterator over the elements
        Iterator<Integer> iterator = collection.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
            val[0] = Collections.max(collection);
            val[1] = Collections.min(collection);
        }
        System.out.println("Max number = "+ val[0]);
        System.out.println("Min number = "+ val[1]);
    }
}

輸出:

71018
8000
1178
1190
Max number = 71018
Min number = 1178

例子3

import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingDeque;
public class JavaCollectionIteratorExample3 {
    public static void main(String[] args) {
        Collection<Character> collection = new LinkedBlockingDeque<Character>();
        for (char c = 'a'; c <= 'z'; c++) {
            collection.add(c);
        }
        System.out.print("Characters:");
        System.out.print("[");
        Iterator<Character> iterator = collection.iterator();
        //will return the iterator for all characters
        while (iterator.hasNext()) {
            System.out.print(iterator.next()+" ,");
        }
        System.out.println("]");
    }
}

輸出:

Characters:[a ,b ,c ,d ,e ,f ,g ,h ,i ,j ,k ,l ,m ,n ,o ,p ,q ,r ,s ,t ,u ,v ,w ,x ,y ,z ,]




相關用法


注:本文由純淨天空篩選整理自 Java Collection iterator() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。