Java LinkedList spliterator()方法
LinkedList 的 spliterator() 方法会返回一个 Spliterator ,该 Spliterator 与LinkedList的元素相同,具有晚期绑定和故障快速性。晚期绑定的Spliterator是指在第一次遍历、第一次拆分或第一次查询估计大小的时候绑定到LinkedList的元素源,而不是在创建Spliterator的时候。它可以在Java 8中与Streams一起使用。同时,它也可以单独或批量地遍历元素。Spliterator是遍历元素的更好方法,因为它提供了对元素的更多控制。
语法
public Spliterator<E> spliterator()
返回: 该方法在LinkedList的元素上返回一个 Spliterator 。
下面的程序说明了LinkedList的splitator()方法。
例子1: 演示LinkedList的splitator()方法,该方法包含一个对象的列表。
// Java Program Demonstrate spliterator()
// method of LinkedList
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an LinkedList which going to
// contains a list of numbers
LinkedList<Shape> shapes = new LinkedList<Shape>();
// Add different shape to linkedlist
shapes.add(new Shape("Circle", 234));
shapes.add(new Shape("Square", 225));
shapes.add(new Shape("Cone", 543));
shapes.add(new Shape("Rectangle", 342));
// create Spliterator of LinkedList
// using spliterator() method
Spliterator<Shape> spliter = shapes.spliterator();
// print result from Spliterator
System.out.println("list of Shapes:");
// forEachRemaining method of Spliterator
spliter.forEachRemaining((Value) -> printDetails(Value));
}
// print details
public static void printDetails(Shape s)
{
System.out.println("************************");
System.out.println("Shape Name : " + s.shapename);
System.out.println("Shape Area : " + s.area);
}
}
// create a shape class
class Shape {
// shape class has two attributes
String shapename;
int area;
public Shape(String shapename, int area)
{
super();
this.shapename = shapename;
this.area = area;
}
}
输出:
list of Shapes:
************************
Shape Name : Circle
Shape Area : 234
************************
Shape Name : Square
Shape Area : 225
************************
Shape Name : Cone
Shape Area : 543
************************
Shape Name : Rectangle
Shape Area : 342
例2: 在包含电影名称列表的LinkedList上演示spliterator()方法。
// Java Program Demonstrate spliterator()
// method of LinkedList
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an LinkedList which going to
// contains a list of Movie names which is actually
// string values
LinkedList<String> NameOfMovies = new LinkedList<String>();
// Add Strings to list
// each string represents city name
NameOfMovies.add("Delhi 6");
NameOfMovies.add("3 Idiots");
NameOfMovies.add("Stree");
NameOfMovies.add("Airlift");
// using spliterator() method
Spliterator<String> names = NameOfMovies.spliterator();
// print result from Spliterator
System.out.println("list of Movies:");
// forEachRemaining method of Spliterator
names.forEachRemaining((n) -> System.out.println("Movie Name: " + n));
}
}
输出:
list of Movies:
Movie Name: Delhi 6
Movie Name: 3 Idiots
Movie Name: Stree
Movie Name: Airlift
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html#spliterator-