LinkedList spliterator() method in Java
The spliterator() method of LinkedList returns a Spliterator which is late-binding and fail-fast with the same elements as LinkedList. A late-binding Spliterator binds to the source of elements means LinkedList at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliterator is created. It can be used with Streams in Java 8. Also it can traverse elements individually and in bulk too. Spliterator is better way to traverse over element because it provides more control on elements. Syntax:
public Spliterator<E> spliterator()
Returns: This method returns a Spliterator over the elements in LinkedList. Below programs illustrate spliterator() method of LinkedList: Example 1: To demonstrate spliterator() method on LinkedList which contains a list of objects.
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
LinkedList<Shape> shapes = new LinkedList<Shape>();
shapes.add( new Shape("Circle", 234 ));
shapes.add( new Shape("Square", 225 ));
shapes.add( new Shape("Cone", 543 ));
shapes.add( new Shape("Rectangle", 342 ));
Spliterator<Shape> splitter = shapes.spliterator();
System.out.println("list of Shapes:");
spliter.forEachRemaining((Value) -> printDetails(Value));
}
public static void printDetails(Shape s)
{
System.out.println("************************");
System.out.println("Shape Name : " + s.shapename);
System.out.println("Shape Area : " + s.area);
}
}
class Shape {
String shapename;
int area;
public Shape(String shapename, int area)
{
super ();
this .shapename = shapename;
this .area = area;
}
}
|
Output:
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
Example 2: To demonstrate spliterator() method on LinkedList which contains list of Movie Names.
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
LinkedList<String> NameOfMovies = new LinkedList<String>();
NameOfMovies.add("Delhi 6 ");
NameOfMovies.add(" 3 Idiots");
NameOfMovies.add("Stree");
NameOfMovies.add("Airlift");
Spliterator<String> names = NameOfMovies.spliterator();
System.out.println("list of Movies:");
names.forEachRemaining((n) -> System.out.println("Movie Name: " + n));
}
}
|
Output:
list of Movies:
Movie Name: Delhi 6
Movie Name: 3 Idiots
Movie Name: Stree
Movie Name: Airlift
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html#spliterator–
Last Updated :
10 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...