1. Introduction

In Java, LinkedList is a class of the Collection Framework that stores elements in a doubly-linked list. Sometimes, we may need to extract a part of this list, i.e., a sublist. The subList(int fromIndex, int toIndex) method is used for this purpose, which returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

2. Program Steps

1. Create and initialize a LinkedList.

2. Use the subList() method to extract a sublist from the LinkedList.

3. Print the original LinkedList and the extracted sublist.

3. Code Program

import java.util.LinkedList;
import java.util.List;

public class LinkedListSubListExample {

    public static void main(String[] args) {

        // Step 1: Create and initialize a LinkedList
        LinkedList<String> animals = new LinkedList<>();
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Elephant");
        animals.add("Lion");
        animals.add("Tiger");

        // Step 2: Use the subList() method to extract a sublist from the LinkedList
        List<String> subList = animals.subList(1, 4);

        // Step 3: Print the original LinkedList and the extracted sublist
        System.out.println("Original LinkedList: " + animals);
        System.out.println("Extracted SubList: " + subList);
    }
}

Output:

Original LinkedList: [Dog, Cat, Elephant, Lion, Tiger]
Extracted SubList: [Cat, Elephant, Lion]

4. Step By Step Explanation

Step 1: A LinkedList named animals is created and initialized with the elements "Dog", "Cat", "Elephant", "Lion", and "Tiger".

Step 2: The subList() method is called on the animals LinkedList, with fromIndex as 1 and toIndex as 4. This method returns a sublist containing the elements from index 1 (inclusive) to index 4 (exclusive) from the original list.

Step 3: The original LinkedList and the extracted subList are printed to the console, demonstrating how to retrieve a sublist from a LinkedList in Java.