当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。