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


Java List spliterator()用法及代码示例


列表接口的 spliterator() 方法在给定列表中的元素上创建一个 Spliterator。

用法

default Spliterator<E> spliterator()

参数

NA

指定者

  • 接口 Collection<E> 中的 spliterator()
  • 接口 Iterable<E> 中的 spliterator()

返回值:

spliterator() 方法在此列表中的元素上返回一个 Spliterator。

例子1

import java.util.LinkedList;
import java.util.List;
import java.util.Spliterator;
public class JavaListSpliteratorExample1 {
public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
for (int i=1;i<=10;i++) {
list.add(i);
        }
System.out.print("Values:");
//spliterator  split and then iterate the split parts in parallel
Spliterator<Integer>str = list.spliterator();
// if the specified element exists then the tryAdvance() will perform the given action
while(str.tryAdvance((n)->System.out.print(n+" ")));
    }
}

输出:

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

例子2

import java.util.LinkedList;
import java.util.List;
import java.util.Spliterator;
class Student{
    String name;
    String school;
    String course;
    Student(String name, String school, String course){
this.name=name;
this.school=school;
this.course=course;
    }
public String toString() {
return  " Name:"+this.name+"     School:"+this.school+"     Course:"+this.course;
    }
}
public class JavaListSpliteratorExample2 {
public static void main(String[] args) {
        List<Student> list = new LinkedList<>();
        Student s1= new Student("Reema","Gita Convent School","Java");
        Student s2= new Student("Geetu","Gita Convent School","Android");
        Student s3= new Student("Saloni","Eicher Public School","Java");
list.add(s1);
list.add(s2);
list.add(s3);
//spliterator  split and then iterate the split parts in parallel
Spliterator<Student>str = list.spliterator();
// if the specified element exists then the tryAdvance() will perform the given action
while(str.tryAdvance((n)->System.out.println(n)));
    }
}

输出:

Name:Reema     School:Gita Convent School     Course:Java
 Name:Geetu     School:Gita Convent School     Course:Android
 Name:Saloni     School:Eicher Public School     Course:Java

例子3

import java.util.LinkedList;
import java.util.List;
import java.util.Spliterator;
public class JavaListSpliteratorExample3 {
public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
for (int i=1;i<=10;i++) {
list.add(i);
        }
System.out.println("Values:");
//spliterator  split and then iterate the split parts in parallel
Spliterator<Integer>str = list.spliterator();
// if the specified element exists then the forEachRemaining() will perform the given action
str.forEachRemaining(System.out::print);
    }
}

输出:

Values:
12345678910




相关用法


注:本文由纯净天空筛选整理自 Java List spliterator() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。