Write a Java program to demonstrate the spliterator() method of LinkedList


The Complex class represents complex numbers with real (re) and imaginary (img) parts. The Demonstrate class contains the main method where a linked list of Complex objects is created and populated with some values.

A Spliterator is then obtained from the linked list using the spliterator() method, which provides a way to traverse and perform operations on the elements of the linked list in a parallel or sequential manner. In this case, the forEachRemaining method of the Spliterator is used to iterate over the linked list and apply the printComplexNumber method to each element, which prints the real and imaginary parts of the complex numbers.

The printComplexNumber method simply prints the real and imaginary parts of a Complex object in the format "re + imgi".

Source Code

import java.util.*;
public class Demonstrate
{
	public static void main(String[] args)
	{
		int i = 0;
		LinkedList <Complex> l = new LinkedList <Complex> ();
 
		l.add(new Complex(10, 20));
		l.add(new Complex(20, 30));
		l.add(new Complex(30, 40));
		l.add(new Complex(40, 50));
		l.add(new Complex(50, 60));
 
		Spliterator <Complex> sp = l.spliterator();
 
		System.out.println("LinkedList .. "); // print result from Spliterator
		sp.forEachRemaining((val) -> printComplexNumber(val));
	}
 
	public static void printComplexNumber(Complex C)
	{
		System.out.println(C.re + " + " + C.img + "i");
	}
}
class Complex
{
	int re, img;
	Complex(int r, int i)
	{
		re = r;
		img = i;
	}
}

Output

LinkedList ..
10 + 20i
20 + 30i
30 + 40i
40 + 50i
50 + 60i

Example Programs