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


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


集合接口的 spliterator() 方法返回一個跨該集合元素的 Spliterator。

用法

public Spliterator<E>spliterator()

參數

NA

指定者

Collection 類的 spliterator() 方法指定為:

  • 接口 Iterable<E> 中的 Spliterator() 方法。

返回值

spliterator() 方法返回一個跨此集合元素的 Spliterator。

例子1

import java.util.Collection;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentLinkedQueue;

public class JavaCollectionSpliteratorExample1 {
static int i=1;
public static void main(String[] args) {
        Collection<Integer> collection = new ConcurrentLinkedQueue();
for (int i=1;i<=10;i++) {
collection.add(i);
        }
System.out.print("Values:");
//spliterator  split and iterate the split parts in parallel
Spliterator<Integer>str = collection.spliterator();
// if element exists tryAdvance() will perform action
while(str.tryAdvance((n)->System.out.print(n+" ")));
    }
}

輸出:

Values:1 2 3 4 5 6 7 8 9 10

例子2

import java.util.Collection;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentLinkedQueue;

public class JavaCollectionSpliteratorExample2 {
static int i = 1;
public static void main(String[] args) {
        Collection<Information> collection = new ConcurrentLinkedQueue();
        Information val1 = new Information("15", "Reema panda", 21);
        Information val2 = new Information("16", "Geetanjali Sharma", 21);
        Information val3 = new Information("17", "Ajeet Kumar Maurya XI", 36);
collection.add(val1);
collection.add(val2);
collection.add(val3);
Spliterator<Information>str = collection.spliterator();
while (str.tryAdvance((n) ->System.out.println(i++ + " ID No = " + n.idNo+ "\n Name = " + n.name + "\n Age = " + n.age+ "\n")))
            ;
    };
}
class Information {
    String idNo, name;
int age;
public Information(String idNo, String name, int age) {
this.idNo= idNo;
this.name = name;
this.age= age;
    }
}

輸出:

1 ID No = 15
 Name = Reema panda
 Age = 21

2 ID No = 16
 Name = Geetanjali Sharma
 Age = 21

3 ID No = 17
 Name = Ajeet Kumar Maurya XI
 Age = 36

例子3

import java.util.Collection;
import java.util.Spliterator;
import java.util.concurrent.ConcurrentLinkedQueue;

public class JavaCollectionSpliteratorExample3 {
static int i=1;
public static void main(String[] args) {
        Collection<Character> collection = new ConcurrentLinkedQueue();
for (char i='A';i<='Z';i++) {
collection.add(i);
        }
System.out.print("Values:");
//spliterator  split and iterate the split parts in parallel
Spliterator<Character>str = collection.spliterator();
// if element exists tryAdvance() will perform action
while(str.tryAdvance((n)->System.out.print(n+" ")));
    }
}

輸出:

Values: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 spliterator() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。